Phase 2 part 3: buying signals, the funnel and the scorecard

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>
This commit is contained in:
2026-11-21 18:06:58 -07:00
co-authored by Claude Opus 5.5
parent ee579ec9f4
commit b025a97e4a
27 changed files with 3031 additions and 53 deletions
+481
View File
@@ -0,0 +1,481 @@
// Package leadsource imports what outside prospecting tools (origami.chat,
// explee.com) learned while testing buying signals: their campaigns (each
// the user assigns to a signal), who they contacted, who replied, who was
// interested, and who unsubscribed. Contacts become funnel events;
// interested people and repliers become prospects to review; unsubscribes
// go on the suppression list. It only reads from the tools.
package leadsource
import (
"context"
"errors"
"math"
"sort"
"strconv"
"strings"
"sync"
"time"
"supermarket/internal/api/explee"
"supermarket/internal/api/origami"
"supermarket/internal/db"
"supermarket/internal/prospects"
"supermarket/internal/signals"
)
// Result is what one import did.
type Result struct {
Source string `json:"source"`
At time.Time `json:"at"`
Campaigns int `json:"campaigns"`
Events int `json:"events"` // new funnel events
Prospects int `json:"prospects"` // new people to review
Suppressed int `json:"suppressed"`
Warnings []string `json:"warnings,omitempty"`
Error string `json:"error,omitempty"`
}
func (r *Result) warn(msg string) {
if len(r.Warnings) < 20 {
r.Warnings = append(r.Warnings, msg)
}
}
// Every is how often imports run on their own.
const Every = 6 * time.Hour
func resultKey(source string) string { return "leadsource:" + source }
// Last is the last import's result for a source, or nil.
func Last(d *db.DB, source string) (*Result, error) {
var r Result
ok, err := d.GetJSON(resultKey(source), &r)
if err != nil || !ok {
return nil, err
}
return &r, nil
}
// one import per source at a time
var running sync.Map
// ErrRunning means an import of that source is already under way.
var ErrRunning = errors.New("an import is already running")
func begin(source string) (func(), error) {
if _, busy := running.LoadOrStore(source, true); busy {
return nil, ErrRunning
}
return func() { running.Delete(source) }, nil
}
func finish(d *db.DB, r *Result, err error) (*Result, error) {
if err != nil {
r.Error = err.Error()
}
if perr := d.PutJSON(resultKey(r.Source), r); perr != nil && err == nil {
err = perr
}
return r, err
}
// importer holds what both imports share.
type importer struct {
d *db.DB
r *Result
now time.Time
}
func (im *importer) event(e signals.Event) {
added, err := signals.Record(im.d, e)
if err != nil {
im.r.warn(err.Error())
}
if added {
im.r.Events++
}
}
// suppress puts an address that unsubscribed on the suppression list.
func (im *importer) suppress(email, reason string) {
if email == "" {
return
}
if sup, err := prospects.IsSuppressed(im.d, email, ""); err != nil || sup {
return
}
if err := prospects.Suppress(im.d, "email", email, reason, im.now); err != nil {
im.r.warn(err.Error())
return
}
im.r.Suppressed++
}
// person is someone an outside tool says is worth reviewing.
type person struct {
first, last, name, title, email, linkedin, phone string
company, domain string
source, detail string
signalID int64
}
// prospect adds a person (and their company) for review, tagged with the
// campaign's signal. Someone already there gets the signal if they had none.
func (im *importer) prospect(p person) {
if p.first == "" && p.last == "" && p.name != "" {
p.first, p.last, _ = strings.Cut(p.name, " ")
if p.last == "" {
p.first, p.last = "", p.first
}
}
if p.first == "" && p.last == "" && p.email == "" {
return
}
var companyID int64
if p.company != "" || p.domain != "" {
name := p.company
if name == "" {
name = p.domain
}
id, added, err := prospects.AddCompany(im.d, prospects.Company{
Name: name, Domain: p.domain, Source: p.source, SourceDetail: p.detail, SignalID: p.signalID,
}, im.now)
switch {
case errors.Is(err, prospects.ErrSuppressed):
return
case err != nil:
im.r.warn(err.Error())
return
}
companyID = id
if !added {
im.tagIfUntagged("company", id, p.signalID)
}
}
id, added, err := prospects.AddContact(im.d, prospects.Contact{
CompanyID: companyID, FirstName: p.first, LastName: p.last, Title: p.title, Email: p.email,
LinkedIn: p.linkedin, Phone: p.phone, Source: p.source, SourceDetail: p.detail, SignalID: p.signalID,
}, im.now)
switch {
case errors.Is(err, prospects.ErrSuppressed):
return
case err != nil:
im.r.warn(err.Error())
return
}
if added {
im.r.Prospects++
} else {
im.tagIfUntagged("contact", id, p.signalID)
}
}
func (im *importer) tagIfUntagged(kind string, id, signalID int64) {
if signalID == 0 {
return
}
var current int64
if kind == "company" {
if c, err := prospects.GetCompany(im.d, id); err == nil {
current = c.SignalID
}
} else if c, err := prospects.GetContact(im.d, id); err == nil {
current = c.SignalID
}
if current == 0 {
if err := prospects.SetSignal(im.d, kind, id, signalID); err != nil {
im.r.warn(err.Error())
}
}
}
func cents(usd float64) int64 { return int64(math.Round(usd * 100)) }
func orNow(t, now time.Time) time.Time {
if t.IsZero() {
return now
}
return t
}
func truncate(s string, n int) string {
s = strings.Join(strings.Fields(s), " ")
if len(s) <= n {
return s
}
return strings.TrimSpace(s[:n]) + "…"
}
// --- explee.com ---
// ImportExplee reads every campaign's numbers and contacted leads, and the
// hot leads.
func ImportExplee(ctx context.Context, d *db.DB, c *explee.Client, now time.Time) (*Result, error) {
r := &Result{Source: signals.SourceExplee, At: now}
done, err := begin(r.Source)
if err != nil {
return r, err
}
defer done()
im := &importer{d: d, r: r, now: now}
camps, err := c.Campaigns(ctx)
if err != nil {
return finish(d, r, err)
}
names := map[int64]string{}
for _, camp := range camps {
if ctx.Err() != nil {
return finish(d, r, ctx.Err())
}
id := strconv.FormatInt(camp.ID, 10)
name := camp.Name
if name == "" {
name = "Campaign " + id
}
names[camp.ID] = name
an, err := c.Analytics(ctx, camp.ID)
if err != nil {
r.warn(name + ": " + err.Error())
an = &explee.Analytics{}
}
status := an.Status
if status == "" {
status = camp.Status
}
if err := signals.SaveCampaign(d, signals.Campaign{
Source: r.Source, ID: id, Name: name, Status: status, SpendCents: cents(an.SpendUSD), SyncedAt: now,
Stats: map[string]any{
"Emails sent": an.EmailsSent, "Replies": an.TotalReplies, "Reply rate %": an.ReplyRatePct,
"Hot leads": an.HotLeads, "Cost per hot lead $": an.CostPerLeadUSD, "Leads contacted": an.LeadsPoolUsed,
"Lost": an.ColdLost, "Booking link": camp.TargetURL,
},
}); err != nil {
return finish(d, r, err)
}
r.Campaigns++
sig, err := signals.CampaignSignal(d, r.Source, id)
if err != nil {
return finish(d, r, err)
}
leads, err := c.Leads(ctx, camp.ID)
if err != nil {
r.warn(name + ": " + err.Error())
}
for _, l := range leads {
if l.PersonID == "" {
continue
}
key := id + ":" + l.PersonID
email := l.Email
if l.Erased {
email = ""
}
base := signals.Event{SignalID: sig, Channel: r.Source, Subject: "explee:" + l.PersonID, Email: email,
Campaign: r.Source + ":" + id, Source: r.Source}
e := base
e.Stage, e.ExternalID, e.At = signals.StageContacted, "contacted:"+key, orNow(origami.ParseTime(l.FirstSentAt), now)
im.event(e)
replyAt := orNow(origami.ParseTime(l.LastReplyAt), now)
if l.Replied {
e := base
e.Stage, e.ExternalID, e.At = signals.StageReplied, "replied:"+key, replyAt
im.event(e)
}
if st := strings.ToLower(l.Status); st == "hot" || st == "won" {
e := base
e.Stage, e.ExternalID, e.At = signals.StageInterested, "interested:"+key, replyAt
im.event(e)
}
if l.Unsubscribed && !l.Erased {
im.suppress(email, "Unsubscribed in explee.com ("+name+")")
}
}
}
hot, err := c.HotLeads(ctx, time.Time{})
if err != nil {
r.warn("hot leads: " + err.Error())
}
for _, h := range hot {
if h.PersonID == "" {
continue
}
id := strconv.FormatInt(h.CampaignID, 10)
sig, _ := signals.CampaignSignal(d, r.Source, id)
email := h.Email
if h.Erased {
email = ""
}
im.event(signals.Event{SignalID: sig, Stage: signals.StageInterested, Channel: r.Source,
Subject: "explee:" + h.PersonID, Email: email, Campaign: r.Source + ":" + id, Source: r.Source,
ExternalID: "interested:" + id + ":" + h.PersonID, At: orNow(origami.ParseTime(h.BecameHotAt), now)})
if h.Erased {
continue
}
detail := "explee.com campaign “" + names[h.CampaignID] + "”"
if h.WhyHot != "" {
detail += ": " + truncate(h.WhyHot, 240)
}
im.prospect(person{name: h.Name, title: h.JobTitle, email: h.Email, linkedin: h.LinkedInURL, phone: h.Phone,
company: h.CompanyName, domain: h.CompanyDomain, source: signals.SourceExplee, detail: detail, signalID: sig})
}
return finish(d, r, nil)
}
// --- origami.chat ---
// contactedStatuses are enrolled people's statuses that mean a message went
// out. Origami's docs don't list them; these are the likely names.
var contactedStatuses = map[string]bool{"active": true, "in_progress": true, "running": true, "sending": true,
"completed": true, "finished": true, "replied": true, "stopped": true, "bounced": true, "unsubscribed": true}
type sequence struct {
campaignID, campaignName string
signalID int64
who origami.Object
}
// ImportOrigami reads every campaign's stats and enrolled people, and the
// replies.
func ImportOrigami(ctx context.Context, d *db.DB, c *origami.Client, now time.Time) (*Result, error) {
r := &Result{Source: signals.SourceOrigami, At: now}
done, err := begin(r.Source)
if err != nil {
return r, err
}
defer done()
im := &importer{d: d, r: r, now: now}
camps, err := c.Campaigns(ctx)
if err != nil {
return finish(d, r, err)
}
seqs := map[string]sequence{}
names := map[string]string{}
for _, camp := range camps {
if ctx.Err() != nil {
return finish(d, r, ctx.Err())
}
id := camp.Str("id")
if id == "" {
continue
}
name := camp.Str("name")
if name == "" {
name = "Campaign " + id
}
names[id] = name
stats, err := c.Stats(ctx, id)
if err != nil {
r.warn(name + ": " + err.Error())
}
if err := signals.SaveCampaign(d, signals.Campaign{
Source: r.Source, ID: id, Name: name, Status: camp.Str("status"), SyncedAt: now, Stats: flatten(stats),
}); err != nil {
return finish(d, r, err)
}
r.Campaigns++
sig, err := signals.CampaignSignal(d, r.Source, id)
if err != nil {
return finish(d, r, err)
}
people, err := c.People(ctx, id)
if err != nil {
r.warn(name + ": " + err.Error())
}
for _, p := range people {
seq := p.Str("sequence_id", "id")
if seq == "" {
continue
}
seqs[seq] = sequence{campaignID: id, campaignName: name, signalID: sig, who: p}
email := strings.ToLower(p.Str("email", "identity.email", "contact.email", "person.email"))
status := strings.ToLower(p.Str("status", "state"))
sentAt := p.Time("first_sent_at", "started_at", "sent_at", "last_sent_at", "last_step_sent_at")
base := signals.Event{SignalID: sig, Channel: r.Source, Subject: "origami:" + seq, Email: email,
Campaign: r.Source + ":" + id, Source: r.Source}
if !sentAt.IsZero() || contactedStatuses[status] {
e := base
e.Stage, e.ExternalID, e.At = signals.StageContacted, "contacted:"+seq, orNow(sentAt, now)
im.event(e)
}
if strings.Contains(status, "unsubscribe") {
im.suppress(email, "Unsubscribed in origami.chat ("+name+")")
}
}
}
replies, err := c.Replies(ctx, time.Time{})
if err != nil {
r.warn("replies: " + err.Error())
}
// Oldest first, so a person's first reply is the one recorded.
sort.SliceStable(replies, func(i, j int) bool {
return replies[i].Time("received_at", "created_at", "sent_at", "date").Before(replies[j].Time("received_at", "created_at", "sent_at", "date"))
})
for _, rep := range replies {
seq := rep.Str("sequence_id", "sequence.id")
info, known := seqs[seq]
campID := rep.Str("campaign_id", "campaign.id")
if campID == "" {
campID = info.campaignID
}
if seq == "" || campID == "" {
continue
}
sig := info.signalID
if !known {
sig, _ = signals.CampaignSignal(d, r.Source, campID)
}
email := strings.ToLower(rep.Str("from_email", "from.email", "email", "lead.email"))
if email == "" && known {
email = strings.ToLower(info.who.Str("email", "identity.email", "contact.email", "person.email"))
}
im.event(signals.Event{SignalID: sig, Stage: signals.StageReplied, Channel: r.Source, Subject: "origami:" + seq,
Email: email, Campaign: r.Source + ":" + campID, Source: r.Source, ExternalID: "replied:" + seq,
At: orNow(rep.Time("received_at", "created_at", "sent_at", "date"), now)})
if !known {
continue
}
w := info.who
detail := "origami.chat campaign “" + names[campID] + "”"
if body := rep.Str("body", "text", "plain_body"); body != "" {
detail += ": " + truncate(body, 240)
}
im.prospect(person{
first: w.Str("first_name", "identity.first_name"), last: w.Str("last_name", "identity.last_name"),
name: w.Str("name", "full_name", "identity.name"), title: w.Str("title", "job_title", "identity.title"),
email: email, linkedin: w.Str("linkedin_url", "identity.linkedin_url", "linkedin"),
company: w.Str("company", "company_name", "identity.company", "identity.company_name"),
domain: w.Str("company_domain", "domain", "identity.company_domain", "identity.domain"),
source: signals.SourceOrigami, detail: detail, signalID: sig,
})
}
return finish(d, r, nil)
}
// flatten keeps a stats object's numbers and short strings, one level of
// nesting deep, for showing.
func flatten(o origami.Object) map[string]any {
out := map[string]any{}
for k, v := range o {
switch x := v.(type) {
case float64, bool:
out[k] = x
case string:
if len(x) < 80 && k != "object" {
out[k] = x
}
case map[string]any:
for k2, v2 := range x {
if f, ok := v2.(float64); ok {
out[k+" "+k2] = f
}
}
}
}
return out
}
+157
View File
@@ -0,0 +1,157 @@
package leadsource
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"path/filepath"
"testing"
"time"
"supermarket/internal/api/explee"
"supermarket/internal/api/origami"
"supermarket/internal/db"
"supermarket/internal/prospects"
"supermarket/internal/signals"
)
func openDB(t *testing.T) *db.DB {
t.Helper()
d, err := db.Open(filepath.Join(t.TempDir(), "app.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { d.Close() })
return d
}
func serve(t *testing.T, key string, routes map[string]any) *httptest.Server {
t.Helper()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("X-API-Key") != key && r.Header.Get("Authorization") != "Bearer "+key {
w.WriteHeader(http.StatusUnauthorized)
return
}
body, ok := routes[r.URL.Path]
if !ok {
t.Errorf("unexpected %s", r.URL)
w.WriteHeader(http.StatusNotFound)
return
}
json.NewEncoder(w).Encode(body)
}))
t.Cleanup(srv.Close)
return srv
}
var now = time.Date(2026, 11, 21, 18, 0, 0, 0, time.UTC)
func TestImportExplee(t *testing.T) {
d := openDB(t)
sig := &signals.Signal{Name: "Price rise", Status: signals.StatusTesting}
signals.Save(d, sig)
srv := serve(t, "k", map[string]any{
"/autogtm/campaigns": map[string]any{"campaigns": []any{
map[string]any{"id": 7, "name": "M365 movers", "status": "outreach", "target_url": "https://cal.example/x"},
}},
"/autogtm/campaigns/7/analytics": map[string]any{"status": "sending", "emails_sent": 40, "total_replies": 3,
"hot_leads": 1, "spend_usd": 12.5},
"/autogtm/campaigns/7/leads": map[string]any{"has_more": false, "leads": []any{
map[string]any{"person_id": "p1", "email": "pat@acme.example", "first_sent_at": "2026-11-01T10:00:00Z",
"replied": true, "last_reply_at": "2026-11-02T09:00:00Z", "status": "Hot"},
map[string]any{"person_id": "p2", "email": "sam@other.example", "first_sent_at": "2026-11-01T10:00:00Z", "unsubscribed": true},
map[string]any{"person_id": "p3", "erased": true, "first_sent_at": "2026-11-01T10:00:00Z"},
}},
"/autogtm/hot-leads": map[string]any{"has_more": false, "leads": []any{
map[string]any{"person_id": "p1", "campaign_id": 7, "name": "Pat Lee", "email": "pat@acme.example",
"job_title": "CTO", "company_name": "Acme", "company_domain": "acme.example",
"why_hot": "Yes, let's talk next week.", "became_hot_at": "2026-11-02T09:05:00Z"},
}},
})
c := explee.New("k").WithBase(srv.URL)
r, err := ImportExplee(context.Background(), d, c, now)
if err != nil {
t.Fatal(err)
}
// 3 contacted + 1 replied + 1 interested (the hot lead repeats it).
if r.Campaigns != 1 || r.Events != 5 || r.Prospects != 1 || r.Suppressed != 1 || len(r.Warnings) != 0 {
t.Fatalf("result: %+v", r)
}
if sup, _ := prospects.IsSuppressed(d, "sam@other.example", ""); !sup {
t.Error("the unsubscribe wasn't suppressed")
}
cs, _, _ := prospects.Review(d, prospects.StatusNew, 0, 10)
if len(cs) != 1 || cs[0].Name != "Acme" || len(cs[0].Contacts) != 1 || cs[0].Contacts[0].Title != "CTO" ||
cs[0].Source != signals.SourceExplee {
t.Fatalf("prospects: %+v", cs)
}
// Assigning the campaign tags its events; the next import tags the
// prospect too, and adds nothing twice.
if err := signals.AssignCampaign(d, signals.SourceExplee, "7", sig.ID); err != nil {
t.Fatal(err)
}
r, err = ImportExplee(context.Background(), d, c, now)
if err != nil || r.Events != 0 || r.Prospects != 0 || r.Suppressed != 0 {
t.Fatalf("second import: %+v %v", r, err)
}
if c, _ := prospects.GetCompany(d, cs[0].ID); c.SignalID != sig.ID || c.Contacts[0].SignalID != sig.ID {
t.Errorf("prospect not tagged: %+v", c)
}
rows, _ := signals.Scorecard(d, signals.Filter{})
if rows[0].Signal.ID != sig.ID || rows[0].Counts[signals.StageContacted] != 3 || rows[0].Counts[signals.StageInterested] != 1 ||
rows[0].SpendCents != 1250 {
t.Errorf("scorecard: %+v spend %d", rows[0].Counts, rows[0].SpendCents)
}
if last, _ := Last(d, signals.SourceExplee); last == nil || last.Campaigns != 1 {
t.Errorf("last: %+v", last)
}
if _, err := ImportExplee(context.Background(), d, explee.New("wrong").WithBase(srv.URL), now); err != explee.ErrUnauthorized {
t.Errorf("bad key: %v", err)
}
}
func TestImportOrigami(t *testing.T) {
d := openDB(t)
srv := serve(t, "og", map[string]any{
"/send/campaigns": map[string]any{"object": "list", "next_cursor": nil, "items": []any{
map[string]any{"object": "campaign", "id": "c1", "name": "Self-hosters", "status": "active"},
}},
"/send/campaigns/c1/stats": map[string]any{"object": "campaign_stats", "sent": 20, "replies": 2,
"rates": map[string]any{"reply": 0.1}},
"/send/campaigns/c1/people": map[string]any{"object": "list", "next_cursor": nil, "items": []any{
map[string]any{"sequence_id": "s1", "status": "replied", "first_name": "Ana", "last_name": "Ruiz",
"email": "ana@coop.example", "company": "Co-op", "company_domain": "coop.example", "first_sent_at": "2026-11-03T08:00:00Z"},
map[string]any{"sequence_id": "s2", "status": "unsubscribed", "email": "no@thanks.example"},
map[string]any{"sequence_id": "s3", "status": "scheduled"},
}},
"/send/replies": map[string]any{"object": "list", "next_cursor": nil, "items": []any{
map[string]any{"sequence_id": "s1", "campaign_id": "c1", "received_at": "2026-11-04T08:00:00Z", "body": "Sounds interesting"},
map[string]any{"sequence_id": "s1", "campaign_id": "c1", "received_at": "2026-11-03T12:00:00Z", "body": "Tell me more"},
}},
})
c := origami.New("og", "").WithBase(srv.URL)
r, err := ImportOrigami(context.Background(), d, c, now)
if err != nil {
t.Fatal(err)
}
// s1 and s2 contacted (s3 is only scheduled), s1 replied once.
if r.Campaigns != 1 || r.Events != 3 || r.Prospects != 1 || r.Suppressed != 1 {
t.Fatalf("result: %+v", r)
}
evs, _ := signals.SubjectEvents(d, "origami:s1")
if len(evs) != 2 || evs[1].Stage != signals.StageReplied || !evs[1].At.Equal(time.Date(2026, 11, 3, 12, 0, 0, 0, time.UTC)) {
t.Errorf("s1 events: %+v", evs)
}
cs, _ := signals.Campaigns(d)
if len(cs) != 1 || cs[0].Stats["sent"] != float64(20) || cs[0].Stats["rates reply"] != 0.1 {
t.Errorf("campaign: %+v", cs)
}
sample, err := c.Sample(context.Background())
if err != nil || sample["campaigns"] != 1 || sample["stats"] == nil {
t.Errorf("sample: %+v %v", sample, err)
}
}