Files
supermarket/internal/signals/signals.go
T
davidandClaude Opus 5.5 c36f786ae9 Fixes from the first round of TEST.md
SEO: a domain property (sc-domain:) covers every subdomain, so the shop,
Gitea and forum were counted as the website. What ranks, the morning
check, the Monday report, keywords, change candidates and the audit's
traffic now read only the website's own host (with or without www).
The report keeps pages worth a proposal apart from "Waiting for your
yes", explains only moves past the thresholds, and says "places up/down".

Also:
- Feed summaries drop the posts' scripts and styles.
- Spend you log can't be negative.
- Test and check buttons can't be clicked twice while they run.
- Previews show the site's web fonts and icon sprites.
- Backups are read without leaving -wal/-shm files; deleting one removes
  them, and leftovers are swept at start.
- The Overview's setup flags a CRM that Hermes can't reach.
- Import now says what came in; adding a prospect that exists says so;
  prospects can be deleted.
- Signal tags and brief addresses keep accented letters (Ü → u).
- Page errors start with a capital; clearer messages for bad uploads,
  CRM retry and cancel, keywords, and the finished audit.
- The module you're in stays unfolded in the sidebar.
- A picked keyword can be unpicked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 06:31:42 -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 {
res, err := d.Exec(`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, err = res.LastInsertId()
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`)
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)
}