Files
supermarket/internal/signals/signals.go
T
davidandClaude Opus 5.5 5f1b8d59ce Phase 9, part 7: export and import, between SQLite and Postgres
supermarket export [--with-secrets] writes a whole Supermarket as a
.tar.gz (a manifest, each table as JSON lines, secrets if asked for) to
the file storage. supermarket import loads one into an empty database at
the same schema, SQLite or Postgres, in one transaction, parents first,
checking row counts and moving Postgres' identity counters past the
imported ids.

Checked on Federated's 112,543 rows: imported into Postgres and SQLite,
every table and total matches, and TestPagesOnRealData renders all 57
pages the same from both. That found unsettled ordering (case-alike
campaigns, customers with the same name, metrics' float sums), now fixed
with ORDER BY and tie-breakers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 08:09:14 -07:00

215 lines
6.0 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"
"strings"
"time"
"supermarket/internal/db"
"supermarket/internal/slug"
)
// 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
DiscoverEveryDays int // find companies on a schedule; 0: only by hand
ExpleeDefinition string // what the companies do, for explee.com's search
}
// 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) }
// Slugify makes a utm_campaign-safe slug from a name.
func Slugify(name string) string {
s := slug.Make(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)
s.ExpleeDefinition = strings.TrimSpace(s.ExpleeDefinition)
if s.DiscoverEveryDays < 0 {
s.DiscoverEveryDays = 0
}
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 {
newID, err := d.Insert(`INSERT INTO signals (slug, name, hypothesis, spot, angle, status, created_at, updated_at,
discover_every_days, explee_definition) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
s.Slug, s.Name, s.Hypothesis, s.Spot, s.Angle, s.Status, now, now, s.DiscoverEveryDays, s.ExpleeDefinition)
if err != nil {
return err
}
s.ID = newID
return err
}
res, err := d.Exec(`UPDATE signals SET slug = ?, name = ?, hypothesis = ?, spot = ?, angle = ?, status = ?, updated_at = ?,
discover_every_days = ?, explee_definition = ? WHERE id = ?`,
s.Slug, s.Name, s.Hypothesis, s.Spot, s.Angle, s.Status, now, s.DiscoverEveryDays, s.ExpleeDefinition, 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, discover_every_days, explee_definition`
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,
&s.DiscoverEveryDays, &s.ExpleeDefinition); 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, id`)
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)
}