Files
supermarket/internal/web/signals.go
T
davidandClaude Opus 5.5 157902f7e2 Phase 2 part 4: discovery per signal (Claude web search, explee.com)
Each signal's page can search for organizations that show it, by hand or
every 7, 14 or 30 days. Claude with the web_search_20260209 server tool
(pause_turn resumed) works from the signal's "How to spot it" lines and
the profile's targets; a company is kept only if its evidence URL was
among the pages searched. explee.com's company search runs the signal's
description in the target sizes, scored against the hypothesis, keeping
strong matches. Our sites, the inventory, existing prospects, CRM
Accounts and suppressed domains are left out. New companies go to Review
tagged with the signal. Schema 8 adds discovery_runs (counts, searches,
why companies were left out) and the signal's schedule and explee.com
description.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 18:27:35 -07:00

631 lines
18 KiB
Go

package web
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"supermarket/internal/ai"
"supermarket/internal/api/explee"
"supermarket/internal/api/origami"
"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
}
s.render(w, r, "signals", page{Title: "Signals", Nav: "prospects/signals", Error: errMsg, Data: map[string]any{
"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
Runs []discovery.Run
Running bool
Research string // why Claude can't search, or ""
ExpleeKey bool
EveryDays []int
MaxSearch int
MaxResults int
}
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
}
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.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(),
}})
}
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, leadSourceKeys); 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
}
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 (" + who + ")."
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 := ai.New(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)
}
}
}
}
}