Files
supermarket/internal/web/signals.go
T
davidandClaude Opus 5.5 e2a72d5ef9 Phase 5 part 5: check the live site after a merge
Merged Sites pages are checked on the live site until they answer with
their own words and title; removed ones until they're gone. The SEO loop,
the page, the signal's page and Sites → Publishing check (or Check now);
two hours without the page points at the deploy hook. Pages going live or
away go to IndexNow. Sites → Publishing lists what's waiting, open pull
requests and recent merges. Schema 24.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 14:28:42 -07:00

759 lines
21 KiB
Go

package web
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"supermarket/internal/sites"
"supermarket/internal/tracking"
"time"
"supermarket/internal/ai"
"supermarket/internal/api/explee"
"supermarket/internal/api/origami"
"supermarket/internal/content"
"supermarket/internal/discovery"
"supermarket/internal/leadsource"
"supermarket/internal/profile"
"supermarket/internal/prospects"
"supermarket/internal/secrets"
"supermarket/internal/signals"
)
// --- The scorecard ---
// periods the scorecard can show.
var periods = []struct{ ID, Label string }{
{"", "All time"}, {"90d", "90 days"}, {"30d", "30 days"}, {"7d", "7 days"},
}
func since(period string, now time.Time) time.Time {
switch period {
case "90d":
return now.AddDate(0, 0, -90)
case "30d":
return now.AddDate(0, 0, -30)
case "7d":
return now.AddDate(0, 0, -7)
}
return time.Time{}
}
func (s *Server) signalsPage(w http.ResponseWriter, r *http.Request) {
s.renderSignals(w, r, "")
}
func (s *Server) renderSignals(w http.ResponseWriter, r *http.Request, errMsg string) {
q := r.URL.Query()
period, channel := q.Get("period"), q.Get("channel")
rows, err := signals.Scorecard(s.DB, signals.Filter{Since: since(period, time.Now()), Channel: channel})
if err != nil {
s.serverError(w, err)
return
}
list, err := signals.List(s.DB)
if err != nil {
s.serverError(w, err)
return
}
camps, err := signals.Campaigns(s.DB)
if err != nil {
s.serverError(w, err)
return
}
live, err := sites.LivePageCounts(s.DB)
if err != nil {
s.serverError(w, err)
return
}
s.render(w, r, "signals", page{Title: "Signals", Nav: "prospects/signals", Error: errMsg, Data: map[string]any{
"LivePages": live,
"Rows": rows,
"Signals": list,
"Stages": signals.Stages,
"Channels": signals.Channels,
"Periods": periods,
"Period": period,
"Channel": channel,
"Campaigns": camps,
"Sources": s.leadSources(),
}})
}
// --- One signal ---
type signalData struct {
S *signals.Signal
Statuses []string
Stages []signals.Stage
ByChannel []channelRow // its funnel per channel
Total *signals.Row
Campaigns []signals.Campaign
Events []signals.Event
Prospects int // new prospects tagged with it
Posts []content.Draft // written for it
Links []string // the websites, tagged with its campaign
Pages []signalPage // its landing pages and their variants
PageSites []siteRepo // websites a landing page can go on
VisitorsErr string // why page visitors couldn't be read
Runs []discovery.Run
Running bool
Research string // why Claude can't search, or ""
ExpleeKey bool
EveryDays []int
MaxSearch int
MaxResults int
}
// signalPage is a landing page on a signal's page.
type signalPage struct {
sites.SitePage
Address string // on the live site
Visitors int // last 30 days; -1 when unknown
}
type channelRow struct {
Channel string
Row signals.Row
}
func (s *Server) signalPage(w http.ResponseWriter, r *http.Request) {
sig := &signals.Signal{Status: signals.StatusIdea}
if idStr := r.PathValue("id"); idStr != "" {
id, err := strconv.ParseInt(idStr, 10, 64)
if err != nil {
http.NotFound(w, r)
return
}
if sig, err = signals.Get(s.DB, id); errors.Is(err, signals.ErrNotFound) {
http.NotFound(w, r)
return
} else if err != nil {
s.serverError(w, err)
return
}
}
s.renderSignal(w, r, sig, "")
}
func (s *Server) renderSignal(w http.ResponseWriter, r *http.Request, sig *signals.Signal, errMsg string) {
d := signalData{S: sig, Statuses: signals.Statuses, Stages: signals.Stages,
EveryDays: []int{0, 7, 14, 30}, MaxSearch: discovery.MaxSearches, MaxResults: discovery.MaxCompanies,
ExpleeKey: s.Secrets.Has(secrets.ExpleeAPIKey)}
if _, err := s.researcher(); err != nil {
d.Research = err.Error()
}
title := "New signal"
if sig.ID != 0 {
title = sig.Name
all, err := signals.Scorecard(s.DB, signals.Filter{})
if err != nil {
s.serverError(w, err)
return
}
for i := range all {
if all[i].Signal != nil && all[i].Signal.ID == sig.ID {
d.Total = &all[i]
}
}
for _, ch := range signals.Channels {
rows, err := signals.Scorecard(s.DB, signals.Filter{Channel: ch.ID})
if err != nil {
s.serverError(w, err)
return
}
for _, row := range rows {
if row.Signal != nil && row.Signal.ID == sig.ID && (row.Total() > 0 || row.SpendCents > 0) {
d.ByChannel = append(d.ByChannel, channelRow{ch.ID, row})
}
}
}
camps, err := signals.Campaigns(s.DB)
if err != nil {
s.serverError(w, err)
return
}
for _, c := range camps {
if c.SignalID == sig.ID {
d.Campaigns = append(d.Campaigns, c)
}
}
if d.Events, err = signals.RecentEvents(s.DB, sig.ID, 30); err != nil {
s.serverError(w, err)
return
}
if err := s.signalPages(r.Context(), sig, &d); err != nil {
s.serverError(w, err)
return
}
cs, ps, err := prospects.Review(s.DB, prospects.StatusNew, sig.ID, 1000)
if err != nil {
s.serverError(w, err)
return
}
d.Prospects = len(cs) + len(ps)
if d.Posts, err = content.ForSignal(s.DB, sig.ID, 20); err != nil {
s.serverError(w, err)
return
}
if p, _ := profile.Load(s.DB); p != nil {
for _, ws := range p.Websites {
if u := tagLink(ws.URL, sig.Slug); u != "" {
d.Links = append(d.Links, u)
}
}
}
if d.Runs, err = discovery.Runs(s.DB, sig.ID, 8); err != nil {
s.serverError(w, err)
return
}
for _, r := range d.Runs {
d.Running = d.Running || r.Status == "running"
}
}
s.render(w, r, "signal", page{Title: title, Nav: "prospects/signals", Error: errMsg, Data: d})
}
func (s *Server) signalSave(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
sig := &signals.Signal{}
if idStr := r.PathValue("id"); idStr != "" {
id, err := strconv.ParseInt(idStr, 10, 64)
if err != nil {
http.NotFound(w, r)
return
}
if sig, err = signals.Get(s.DB, id); err != nil {
http.NotFound(w, r)
return
}
}
f := r.PostFormValue
sig.Name, sig.Slug, sig.Hypothesis, sig.Spot, sig.Angle, sig.Status =
f("name"), f("slug"), f("hypothesis"), f("spot"), f("angle"), f("status")
sig.ExpleeDefinition = f("explee_definition")
sig.DiscoverEveryDays, _ = strconv.Atoi(f("discover_every_days"))
if err := signals.Save(s.DB, sig); err != nil {
s.renderSignal(w, r, sig, err.Error())
return
}
redirect(w, r, "/signals/"+strconv.FormatInt(sig.ID, 10), "saved")
}
func (s *Server) signalDelete(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
http.NotFound(w, r)
return
}
if err := signals.Delete(s.DB, id); err != nil {
s.serverError(w, err)
return
}
redirect(w, r, "/signals", "deleted")
}
// signalCampaign assigns an outside campaign to a signal.
func (s *Server) signalCampaign(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
sig, _ := strconv.ParseInt(r.PostFormValue("signal"), 10, 64)
if err := signals.AssignCampaign(s.DB, r.PostFormValue("source"), r.PostFormValue("id"), sig); err != nil {
s.renderSignals(w, r, err.Error())
return
}
redirect(w, r, "/signals#campaigns", "saved")
}
// --- Outcomes recorded by hand ---
// prospectOutcome records a funnel step for a prospect: until Supermarket
// sends and reads its own outreach, this is how replies, bookings and
// payments get onto the scorecard.
func (s *Server) prospectOutcome(w http.ResponseWriter, r *http.Request, kind string, id int64, tab string) error {
var subject, email string
var sig int64
if kind == "company" {
c, err := prospects.GetCompany(s.DB, id)
if err != nil {
return err
}
subject, sig = prospects.Subject(kind, id), c.SignalID
} else {
c, err := prospects.GetContact(s.DB, id)
if err != nil {
return err
}
subject, sig, email = prospects.Subject(kind, id), c.SignalID, c.Email
}
var value int64
if amount := strings.TrimSpace(strings.TrimPrefix(r.PostFormValue("amount"), "$")); amount != "" {
f, err := strconv.ParseFloat(strings.ReplaceAll(amount, ",", ""), 64)
if err != nil || f < 0 {
return fmt.Errorf("%q isn't an amount", amount)
}
value = int64(f*100 + 0.5)
}
at := time.Now()
if day := r.PostFormValue("date"); day != "" {
t, err := time.ParseInLocation("2006-01-02", day, time.Local)
if err != nil {
return fmt.Errorf("%q isn't a date", day)
}
at = t.Add(12 * time.Hour)
}
_, err := signals.Record(s.DB, signals.Event{
SignalID: sig, Stage: r.PostFormValue("stage"), Channel: r.PostFormValue("channel"), Subject: subject,
Email: email, Source: signals.SourceManual, ValueCents: value, Note: r.PostFormValue("note"), At: at,
})
return err
}
func (s *Server) funnelDelete(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
http.NotFound(w, r)
return
}
if err := signals.DeleteEvent(s.DB, id); err != nil {
s.renderProspects(w, r, reviewTab(r.PostFormValue("tab")), 0, err.Error())
return
}
back := r.PostFormValue("back")
if !strings.HasPrefix(back, "/") || strings.HasPrefix(back, "//") {
back = "/prospects"
}
redirect(w, r, back, "deleted")
}
// --- Lead sources: origami.chat and explee.com ---
const origamiProjectKey = "leadsource:origami-project"
// leadSource is one tool, as the pages show it.
type leadSource struct {
ID, Name, Site string
Key secretField
Set bool
Last *leadsource.Result
}
var leadSourceKeys = []secretField{
{"origami", secrets.OrigamiAPIKey, "API key",
"In origami.chat, Settings → Developers → Create API key, with Full API access. It starts og_live_ and is shown once.", "https://origami.chat"},
{"explee", secrets.ExpleeAPIKey, "API key",
"In explee.com, Organization Settings → API keys.", "https://explee.com/app-auto-gtm/api-keys"},
}
func (s *Server) leadSources() []leadSource {
out := []leadSource{
{ID: signals.SourceOrigami, Name: "origami.chat", Site: "https://origami.chat", Key: leadSourceKeys[0]},
{ID: signals.SourceExplee, Name: "explee.com", Site: "https://explee.com", Key: leadSourceKeys[1]},
}
for i := range out {
out[i].Set = s.Secrets.Has(out[i].Key.Name)
out[i].Last, _ = leadsource.Last(s.DB, out[i].ID)
}
return out
}
func (s *Server) origamiProject() string {
var p string
_, _ = s.DB.GetJSON(origamiProjectKey, &p)
return p
}
func (s *Server) sourcesPage(w http.ResponseWriter, r *http.Request) {
s.render(w, r, "sources", page{Title: "Lead sources", Nav: "settings/sources", Data: map[string]any{
"Sources": s.leadSources(),
"Project": s.origamiProject(),
"Hunter": s.hunterSettingsData(),
}})
}
func (s *Server) sourcesSave(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err := s.saveSecrets(r, append(leadSourceKeys, hunterKey)); err != nil {
s.serverError(w, err)
return
}
if err := s.DB.PutJSON(origamiProjectKey, strings.TrimSpace(r.PostFormValue("origami_project"))); err != nil {
s.serverError(w, err)
return
}
if err := s.saveHunterSettings(r); err != nil {
s.serverError(w, err)
return
}
redirect(w, r, "/settings/sources", "saved")
}
// sourcesTest checks a key, and for origami.chat shows what the API sends,
// since its responses aren't documented.
func (s *Server) sourcesTest(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 60*time.Second)
defer cancel()
data := map[string]any{}
switch r.PathValue("source") {
case signals.SourceExplee:
key := s.Secrets.Get(secrets.ExpleeAPIKey)
if key == "" {
data["Error"] = "Save the key first."
break
}
who, err := explee.New(key).Me(ctx)
if err != nil {
data["Error"] = err.Error()
break
}
data["OK"] = "The key works."
if who != "" {
data["OK"] = "The key works (" + who + ")."
}
case "hunter":
data = s.testHunter(ctx)
case signals.SourceOrigami:
key := s.Secrets.Get(secrets.OrigamiAPIKey)
if key == "" {
data["Error"] = "Save the key first."
break
}
c := origami.New(key, s.origamiProject())
who, err := c.Account(ctx)
if err != nil {
data["Error"] = err.Error()
break
}
data["OK"] = "The key works (" + who + ")."
if sample, err := c.Sample(ctx); err == nil {
raw, _ := json.MarshalIndent(sample, "", " ")
data["Sample"] = string(raw)
}
default:
http.NotFound(w, r)
return
}
s.fragment(w, "sources", "test-result", data)
}
// importSource runs one tool's import now.
func (s *Server) importSource(w http.ResponseWriter, r *http.Request) {
source := r.PathValue("source")
if source != signals.SourceExplee && source != signals.SourceOrigami {
http.NotFound(w, r)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Minute)
defer cancel()
res, err := s.runImport(ctx, source)
if err != nil && res == nil {
s.renderSignals(w, r, err.Error())
return
}
if err != nil {
s.renderSignals(w, r, "Importing from "+source+": "+err.Error())
return
}
redirect(w, r, "/signals#campaigns", "imported")
}
// runImport imports from one tool, if its key is saved. It returns nil, nil
// without one.
func (s *Server) runImport(ctx context.Context, source string) (*leadsource.Result, error) {
now := time.Now()
switch source {
case signals.SourceExplee:
if key := s.Secrets.Get(secrets.ExpleeAPIKey); key != "" {
return leadsource.ImportExplee(ctx, s.DB, explee.New(key), now)
}
case signals.SourceOrigami:
if key := s.Secrets.Get(secrets.OrigamiAPIKey); key != "" {
return leadsource.ImportOrigami(ctx, s.DB, origami.New(key, s.origamiProject()), now)
}
}
return nil, errors.New("save the tool's API key first, under Settings → Lead sources")
}
// RunImports imports from each tool with a saved key, every
// leadsource.Every.
func (s *Server) RunImports(ctx context.Context) {
tick := time.NewTicker(10 * time.Minute)
defer tick.Stop()
for {
for _, src := range []string{signals.SourceOrigami, signals.SourceExplee} {
last, _ := leadsource.Last(s.DB, src)
if last != nil && time.Since(last.At) < leadsource.Every {
continue
}
ictx, cancel := context.WithTimeout(ctx, 10*time.Minute)
res, err := s.runImport(ictx, src)
cancel()
switch {
case res == nil:
case err != nil:
s.Log.Warn("lead source import failed", "source", src, "err", err)
default:
s.Log.Info("lead source imported", "source", src, "campaigns", res.Campaigns, "events", res.Events,
"prospects", res.Prospects, "suppressed", res.Suppressed)
}
}
select {
case <-ctx.Done():
return
case <-tick.C:
}
}
}
// --- Discovery ---
// researcher is the AI client, if it can search the web.
func (s *Server) researcher() (ai.Researcher, error) {
cfg, err := ai.LoadConfig(s.DB)
if err != nil {
return nil, err
}
c, err := newAIClient(cfg, s.Secrets)
if err != nil {
return nil, err
}
r, ok := c.(ai.Researcher)
if !ok {
return nil, ai.ErrNoResearch
}
return r, nil
}
// discoverTimeout bounds one run: several web searches and a long reply.
const discoverTimeout = 15 * time.Minute
// discover runs one search for a signal. It runs in the background, since
// it takes minutes; the signal's page shows its progress.
func (s *Server) discover(sig *signals.Signal, source string) error {
prof, err := profile.Load(s.DB)
if err != nil {
return err
}
var run func(ctx context.Context) (*discovery.Run, error)
switch source {
case discovery.SourceClaude:
r, err := s.researcher()
if err != nil {
return err
}
run = func(ctx context.Context) (*discovery.Run, error) {
return discovery.FindWithClaude(ctx, s.DB, r, sig, prof, time.Now())
}
case discovery.SourceExplee:
key := s.Secrets.Get(secrets.ExpleeAPIKey)
if key == "" {
return errors.New("save your explee.com API key first, under Settings → Lead sources")
}
if strings.TrimSpace(sig.ExpleeDefinition) == "" {
return errors.New("describe what the companies do, for explee.com, in the signal's form below")
}
run = func(ctx context.Context) (*discovery.Run, error) {
return discovery.FindWithExplee(ctx, s.DB, explee.New(key), sig, prof, time.Now())
}
default:
return errors.New("unknown source")
}
started := make(chan error, 1)
go func() {
ctx, cancel := context.WithTimeout(context.Background(), discoverTimeout)
defer cancel()
res, err := run(ctx)
if res == nil {
started <- err // didn't start: already running
return
}
started <- nil
if err != nil {
s.Log.Warn("discovery failed", "signal", sig.ID, "source", source, "err", err)
return
}
s.Log.Info("discovery finished", "signal", sig.ID, "source", source, "found", res.Found, "added", res.Added,
"searches", res.Searches)
}()
// Wait briefly, to report a run that couldn't start.
select {
case err := <-started:
return err
case <-time.After(1500 * time.Millisecond):
return nil
}
}
func (s *Server) signalDiscover(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
http.NotFound(w, r)
return
}
sig, err := signals.Get(s.DB, id)
if err != nil {
http.NotFound(w, r)
return
}
if err := s.discover(sig, r.PathValue("source")); err != nil {
s.renderSignal(w, r, sig, err.Error())
return
}
redirect(w, r, "/signals/"+strconv.FormatInt(id, 10)+"#discovery", "discovering")
}
// signalRuns is the discovery card's run list, polled while a run is going.
func (s *Server) signalRuns(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
http.NotFound(w, r)
return
}
runs, err := discovery.Runs(s.DB, id, 8)
if err != nil {
s.serverError(w, err)
return
}
running := false
for _, run := range runs {
running = running || run.Status == "running"
}
s.fragment(w, "signal", "runs", map[string]any{"ID": id, "Runs": runs, "Running": running})
}
// RunDiscovery searches for signals that ask to be searched on a schedule.
func (s *Server) RunDiscovery(ctx context.Context) {
if err := discovery.RecoverInterrupted(s.DB); err != nil {
s.Log.Error("discovery: recovering interrupted runs", "err", err)
}
tick := time.NewTicker(30 * time.Minute)
defer tick.Stop()
for {
select {
case <-ctx.Done():
return
case <-tick.C:
}
list, err := signals.List(s.DB)
if err != nil {
s.Log.Error("discovery: listing signals", "err", err)
continue
}
for i := range list {
sig := &list[i]
if sig.DiscoverEveryDays <= 0 || sig.Status == signals.StatusRetired {
continue
}
due := time.Duration(sig.DiscoverEveryDays) * 24 * time.Hour
sources := []string{discovery.SourceClaude}
if sig.ExpleeDefinition != "" && s.Secrets.Has(secrets.ExpleeAPIKey) {
sources = append(sources, discovery.SourceExplee)
}
for _, src := range sources {
last, err := discovery.LastStarted(s.DB, sig.ID, src)
if err != nil || time.Since(last) < due {
continue
}
if err := s.discover(sig, src); err != nil {
s.Log.Warn("discovery: scheduled run didn't start", "signal", sig.ID, "source", src, "err", err)
}
}
}
}
}
// tagLink is a website's address with a signal's campaign tag, for
// landing pages, the shopping cart and links placed by hand.
func tagLink(site, slug string) string {
u, err := url.Parse(strings.TrimSpace(site))
if err != nil || u.Host == "" {
return ""
}
q := u.Query()
q.Set("utm_campaign", slug)
u.RawQuery = q.Encode()
return u.String()
}
// signalPages fills in a signal's landing pages: their state on Gitea
// (merged, closed), and each live one's visitors over 30 days.
func (s *Server) signalPages(ctx context.Context, sig *signals.Signal, d *signalData) error {
ps, err := sites.SignalPages(s.DB, sig.ID)
if err != nil {
return err
}
for _, sr := range s.siteRepos() {
if sr.Repo != "" {
d.PageSites = append(d.PageSites, sr)
}
}
if s.gitea() != nil {
gctx, cancel := context.WithTimeout(ctx, 15*time.Second)
for i := range ps {
if ps[i].Status == sites.PagePR || ps[i].Status == sites.PageRemoving {
s.refreshPagePR(gctx, &ps[i])
}
}
cancel()
}
lctx, lcancel := context.WithTimeout(ctx, 15*time.Second)
for i := range ps {
if ps[i].Waiting() && time.Since(ps[i].CheckedAt) > time.Minute {
sites.CheckLive(lctx, s.liveFetcher(), &ps[i], time.Now())
_ = sites.SavePage(s.DB, &ps[i])
}
}
lcancel()
prof, _ := profile.Load(s.DB)
bySite := map[string][]string{}
for _, p := range ps {
if p.Live() {
bySite[p.Site] = append(bySite[p.Site], p.Path)
}
}
visitors := map[string]map[string]int{}
if pl := s.plausible(); pl != nil && prof != nil && len(bySite) > 0 {
pctx, cancel := context.WithTimeout(ctx, 15*time.Second)
for _, w := range prof.Websites {
paths := bySite[w.URL]
if len(paths) == 0 {
continue
}
v, err := tracking.PageVisitors(pctx, pl, tracking.SiteID(w), paths)
if err != nil {
d.VisitorsErr = err.Error()
continue
}
visitors[w.URL] = v
}
cancel()
}
for _, p := range ps {
sp := signalPage{SitePage: p, Visitors: -1}
if p.Live() {
sp.Address = strings.TrimRight(p.Site, "/") + p.Path
if v, ok := visitors[p.Site]; ok {
sp.Visitors = v[p.Path]
}
}
d.Pages = append(d.Pages, sp)
}
return nil
}