Files
supermarket/internal/signals/signals.go
T
davidandClaude Opus 5.5 b025a97e4a 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>
2026-11-21 18:06:58 -07:00

207 lines
5.5 KiB
Go

// Package signals keeps the buying signals (hypotheses about why a company
// buys now) and the funnel: every step someone takes, from being found to
// paying, recorded as an event tagged with a signal and a channel. The
// scorecard counts them, so signals can be tested against what was done
// for them, directly (email, LinkedIn) and indirectly (posts, pages).
package signals
import (
"database/sql"
"errors"
"fmt"
"regexp"
"strings"
"time"
"supermarket/internal/db"
)
// Statuses of a signal, in order.
const (
StatusIdea = "idea"
StatusTesting = "testing"
StatusProven = "proven"
StatusRetired = "retired"
)
var Statuses = []string{StatusIdea, StatusTesting, StatusProven, StatusRetired}
// Signal is one buying signal.
type Signal struct {
ID int64
Slug string // utm_campaign
Name string
Hypothesis string
Spot string // how to find it: queries and keywords, one per line
Angle string // the pain and promise for messages and content
Status string
CreatedAt time.Time
UpdatedAt time.Time
}
// SpotLines are the non-empty lines of Spot.
func (s *Signal) SpotLines() []string {
var out []string
for _, l := range strings.Split(s.Spot, "\n") {
if l = strings.TrimSpace(l); l != "" {
out = append(out, l)
}
}
return out
}
// ErrNotFound means there's no signal with that ID.
var ErrNotFound = errors.New("no such signal")
const timeFormat = time.RFC3339
func formatTime(t time.Time) string { return t.UTC().Format(timeFormat) }
var nonSlug = regexp.MustCompile(`[^a-z0-9]+`)
// Slugify makes a utm_campaign-safe slug from a name.
func Slugify(name string) string {
s := strings.Trim(nonSlug.ReplaceAllString(strings.ToLower(name), "-"), "-")
if len(s) > 60 {
s = strings.TrimRight(s[:60], "-")
}
return s
}
func validStatus(s string) bool {
for _, st := range Statuses {
if s == st {
return true
}
}
return false
}
// Save creates or updates a signal. An empty slug is made from the name;
// slugs are unique, so a taken one gets a number.
func Save(d *db.DB, s *Signal) error {
s.Name = strings.TrimSpace(s.Name)
s.Hypothesis = strings.TrimSpace(s.Hypothesis)
s.Spot = strings.TrimSpace(s.Spot)
s.Angle = strings.TrimSpace(s.Angle)
if s.Name == "" {
return errors.New("a signal needs a name")
}
if s.Status == "" {
s.Status = StatusIdea
}
if !validStatus(s.Status) {
return fmt.Errorf("unknown status %q", s.Status)
}
s.Slug = Slugify(s.Slug)
if s.Slug == "" {
s.Slug = Slugify(s.Name)
}
if s.Slug == "" {
return errors.New("the name needs some letters or digits, for the campaign tag")
}
base := s.Slug
for i := 2; ; i++ {
var other int64
err := d.QueryRow(`SELECT id FROM signals WHERE slug = ?`, s.Slug).Scan(&other)
if errors.Is(err, sql.ErrNoRows) || other == s.ID {
break
}
if err != nil {
return err
}
s.Slug = fmt.Sprintf("%s-%d", base, i)
}
now := formatTime(time.Now())
if s.ID == 0 {
res, err := d.Exec(`INSERT INTO signals (slug, name, hypothesis, spot, angle, status, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, s.Slug, s.Name, s.Hypothesis, s.Spot, s.Angle, s.Status, now, now)
if err != nil {
return err
}
s.ID, err = res.LastInsertId()
return err
}
res, err := d.Exec(`UPDATE signals SET slug = ?, name = ?, hypothesis = ?, spot = ?, angle = ?, status = ?, updated_at = ?
WHERE id = ?`, s.Slug, s.Name, s.Hypothesis, s.Spot, s.Angle, s.Status, now, s.ID)
if err != nil {
return err
}
if n, _ := res.RowsAffected(); n == 0 {
return ErrNotFound
}
return nil
}
// Delete removes a signal. Its prospects, campaigns and events stay, without
// a signal.
func Delete(d *db.DB, id int64) error {
_, err := d.Exec(`DELETE FROM signals WHERE id = ?`, id)
return err
}
const columns = `id, slug, name, hypothesis, spot, angle, status, created_at, updated_at`
func scan(rows *sql.Rows) ([]Signal, error) {
defer rows.Close()
var out []Signal
for rows.Next() {
var s Signal
var created, updated string
if err := rows.Scan(&s.ID, &s.Slug, &s.Name, &s.Hypothesis, &s.Spot, &s.Angle, &s.Status, &created, &updated); err != nil {
return nil, err
}
s.CreatedAt, _ = time.Parse(timeFormat, created)
s.UpdatedAt, _ = time.Parse(timeFormat, updated)
out = append(out, s)
}
return out, rows.Err()
}
// Get returns one signal.
func Get(d *db.DB, id int64) (*Signal, error) {
rows, err := d.Query(`SELECT `+columns+` FROM signals WHERE id = ?`, id)
if err != nil {
return nil, err
}
ss, err := scan(rows)
if err != nil {
return nil, err
}
if len(ss) == 0 {
return nil, ErrNotFound
}
return &ss[0], nil
}
// List returns every signal: in testing first, then ideas, proven and
// retired; by name within each.
func List(d *db.DB) ([]Signal, error) {
rows, err := d.Query(`SELECT ` + columns + ` FROM signals ORDER BY
CASE status WHEN 'testing' THEN 0 WHEN 'idea' THEN 1 WHEN 'proven' THEN 2 ELSE 3 END, name COLLATE NOCASE`)
if err != nil {
return nil, err
}
return scan(rows)
}
// Search finds signals containing every (lower-case) word.
func Search(d *db.DB, words []string, limit int) ([]Signal, error) {
if len(words) == 0 {
return nil, nil
}
hay := "lower(name || ' ' || slug || ' ' || hypothesis || ' ' || spot || ' ' || angle)"
conds := make([]string, len(words))
args := make([]any, 0, len(words)+1)
for i, w := range words {
conds[i] = "instr(" + hay + ", ?) > 0"
args = append(args, w)
}
rows, err := d.Query(`SELECT `+columns+` FROM signals WHERE `+strings.Join(conds, " AND ")+` ORDER BY name LIMIT ?`,
append(args, limit)...)
if err != nil {
return nil, err
}
return scan(rows)
}