Files
supermarket/internal/signals/funnel.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

433 lines
12 KiB
Go

package signals
import (
"database/sql"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"supermarket/internal/db"
)
// Stages of the funnel, in order. Each is a success where it happens.
const (
StageFound = "found" // a prospect turned up
StageContacted = "contacted" // an email or message went out, or a post reached them
StageReplied = "replied" // they wrote back
StageInterested = "interested" // the reply was positive (a "hot lead")
StageBooked = "booked" // clicked the scheduling link, or booked
StageVisited = "visited" // came to the website or a landing page
StageSignedUp = "signed_up" // a trial or the free tier
StagePaid = "paid" // the biggest success
)
// Stage is a funnel stage and how it's shown.
type Stage struct{ ID, Label string }
var Stages = []Stage{
{StageFound, "Found"},
{StageContacted, "Contacted"},
{StageReplied, "Replied"},
{StageInterested, "Interested"},
{StageBooked, "Booked"},
{StageVisited, "Visited"},
{StageSignedUp, "Signed up"},
{StagePaid, "Paid"},
}
// StageLabel is how a stage is shown.
func StageLabel(id string) string {
for _, s := range Stages {
if s.ID == id {
return s.Label
}
}
return id
}
func validStage(id string) bool {
for _, s := range Stages {
if s.ID == id {
return true
}
}
return false
}
// Channels: direct (email, LinkedIn), indirect (social, blog, website), and
// the outside tools.
var Channels = []Stage{
{"email", "Email"},
{"linkedin", "LinkedIn"},
{"social", "Social posts"},
{"blog", "Blog"},
{"website", "Website"},
{"origami", "origami.chat"},
{"explee", "explee.com"},
{"other", "Other"},
}
// ChannelLabel is how a channel is shown.
func ChannelLabel(id string) string {
for _, c := range Channels {
if c.ID == id {
return c.Label
}
}
return id
}
func validChannel(id string) bool {
for _, c := range Channels {
if c.ID == id {
return true
}
}
return false
}
// Event sources.
const (
SourceSupermarket = "supermarket" // recorded by Supermarket itself
SourceManual = "manual" // recorded by the user
SourceOrigami = "origami"
SourceExplee = "explee"
)
// Event is one step through the funnel.
type Event struct {
ID int64
SignalID int64 // 0: none
Stage string
Channel string
Subject string // contact:12, company:3, explee:<person>…
Email string
Campaign string // origami:<id>, explee:<id>
Source string
ExternalID string // dedupes imports: the same ID is recorded once
Count int // 1 for a person; more for aggregate numbers
ValueCents int64 // for paid
Note string
At time.Time
}
func nullID(id int64) any {
if id == 0 {
return nil
}
return id
}
// Record stores an event. One with an external ID already recorded from the
// same source is skipped, and added is false.
func Record(d *db.DB, e Event) (added bool, err error) {
if !validStage(e.Stage) {
return false, fmt.Errorf("unknown stage %q", e.Stage)
}
if !validChannel(e.Channel) {
return false, fmt.Errorf("unknown channel %q", e.Channel)
}
if e.Source == "" {
return false, errors.New("an event needs a source")
}
if e.Count <= 0 {
e.Count = 1
}
if e.At.IsZero() {
e.At = time.Now()
}
res, err := d.Exec(`INSERT INTO funnel_events (signal_id, stage, channel, subject, email, campaign, source, external_id,
count, value_cents, note, at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (source, external_id) WHERE external_id != '' DO NOTHING`,
nullID(e.SignalID), e.Stage, e.Channel, e.Subject, strings.ToLower(strings.TrimSpace(e.Email)), e.Campaign, e.Source,
e.ExternalID, e.Count, e.ValueCents, strings.TrimSpace(e.Note), formatTime(e.At))
if err != nil {
return false, err
}
n, _ := res.RowsAffected()
return n > 0, nil
}
// DeleteEvent removes an event the user recorded by hand.
func DeleteEvent(d *db.DB, id int64) error {
res, err := d.Exec(`DELETE FROM funnel_events WHERE id = ? AND source = 'manual'`, id)
if err != nil {
return err
}
if n, _ := res.RowsAffected(); n == 0 {
return errors.New("only outcomes you recorded yourself can be removed")
}
return nil
}
const eventColumns = `id, coalesce(signal_id, 0), stage, channel, subject, email, campaign, source, external_id,
count, value_cents, note, at`
func scanEvents(rows *sql.Rows) ([]Event, error) {
defer rows.Close()
var out []Event
for rows.Next() {
var e Event
var at string
if err := rows.Scan(&e.ID, &e.SignalID, &e.Stage, &e.Channel, &e.Subject, &e.Email, &e.Campaign, &e.Source,
&e.ExternalID, &e.Count, &e.ValueCents, &e.Note, &at); err != nil {
return nil, err
}
e.At, _ = time.Parse(timeFormat, at)
out = append(out, e)
}
return out, rows.Err()
}
// SubjectEvents are the events about these subjects, oldest first.
func SubjectEvents(d *db.DB, subjects ...string) ([]Event, error) {
if len(subjects) == 0 {
return nil, nil
}
args := make([]any, len(subjects))
for i, s := range subjects {
args[i] = s
}
rows, err := d.Query(`SELECT `+eventColumns+` FROM funnel_events WHERE subject IN (?`+
strings.Repeat(", ?", len(subjects)-1)+`) ORDER BY at, id`, args...)
if err != nil {
return nil, err
}
return scanEvents(rows)
}
// RecentEvents are the newest events, for a signal (0: all).
func RecentEvents(d *db.DB, signalID int64, limit int) ([]Event, error) {
q := `SELECT ` + eventColumns + ` FROM funnel_events`
args := []any{}
if signalID != 0 {
q += ` WHERE signal_id = ?`
args = append(args, signalID)
}
rows, err := d.Query(q+` ORDER BY at DESC, id DESC LIMIT ?`, append(args, limit)...)
if err != nil {
return nil, err
}
return scanEvents(rows)
}
// RetagSubject moves a subject's events to another signal, when its
// prospect's signal changes. Events from a campaign keep the campaign's.
func RetagSubject(d *db.DB, subject string, signalID int64) error {
_, err := d.Exec(`UPDATE funnel_events SET signal_id = ? WHERE subject = ? AND campaign = ''`, nullID(signalID), subject)
return err
}
// --- Campaigns in outside tools ---
// Campaign is a campaign in origami.chat or explee.com.
type Campaign struct {
Source string
ID string
Name string
Status string
SignalID int64
SpendCents int64
Stats map[string]any
SyncedAt time.Time
}
// Key is how events refer to the campaign.
func (c *Campaign) Key() string { return c.Source + ":" + c.ID }
// SaveCampaign stores what a tool says about a campaign, keeping the signal
// the user gave it.
func SaveCampaign(d *db.DB, c Campaign) error {
stats, err := json.Marshal(c.Stats)
if err != nil {
return err
}
_, err = d.Exec(`INSERT INTO outside_campaigns (source, id, name, status, spend_cents, stats, synced_at)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (source, id) DO UPDATE SET name = excluded.name, status = excluded.status,
spend_cents = excluded.spend_cents, stats = excluded.stats, synced_at = excluded.synced_at`,
c.Source, c.ID, c.Name, c.Status, c.SpendCents, string(stats), formatTime(c.SyncedAt))
return err
}
// CampaignSignal is the signal a campaign is assigned to, or 0.
func CampaignSignal(d *db.DB, source, id string) (int64, error) {
var sig int64
err := d.QueryRow(`SELECT coalesce(signal_id, 0) FROM outside_campaigns WHERE source = ? AND id = ?`, source, id).Scan(&sig)
if errors.Is(err, sql.ErrNoRows) {
return 0, nil
}
return sig, err
}
// AssignCampaign gives a campaign a signal (0: none), and moves its events.
func AssignCampaign(d *db.DB, source, id string, signalID int64) error {
tx, err := d.Begin()
if err != nil {
return err
}
defer tx.Rollback()
res, err := tx.Exec(`UPDATE outside_campaigns SET signal_id = ? WHERE source = ? AND id = ?`, nullID(signalID), source, id)
if err != nil {
return err
}
if n, _ := res.RowsAffected(); n == 0 {
return errors.New("no such campaign")
}
if _, err := tx.Exec(`UPDATE funnel_events SET signal_id = ? WHERE campaign = ?`, nullID(signalID), source+":"+id); err != nil {
return err
}
return tx.Commit()
}
// Campaigns lists the outside campaigns, unassigned first, newest sync first.
func Campaigns(d *db.DB) ([]Campaign, error) {
rows, err := d.Query(`SELECT source, id, name, status, coalesce(signal_id, 0), spend_cents, stats, synced_at
FROM outside_campaigns ORDER BY signal_id IS NOT NULL, source, name COLLATE NOCASE, id`)
if err != nil {
return nil, err
}
defer rows.Close()
var out []Campaign
for rows.Next() {
var c Campaign
var stats, synced string
if err := rows.Scan(&c.Source, &c.ID, &c.Name, &c.Status, &c.SignalID, &c.SpendCents, &stats, &synced); err != nil {
return nil, err
}
_ = json.Unmarshal([]byte(stats), &c.Stats)
c.SyncedAt, _ = time.Parse(timeFormat, synced)
out = append(out, c)
}
return out, rows.Err()
}
// --- The scorecard ---
// Row is one signal's line on the scorecard.
type Row struct {
Signal *Signal // nil: events without a signal
Counts map[string]int
RevenueCents int64
SpendCents int64 // what the outside tools report spending on its campaigns (lifetime)
}
// Cell is one stage's number on a row.
type Cell struct {
Stage string
Count int
Rate string // as a share of those contacted, for later stages
}
// Cells are the row's numbers in stage order.
func (r *Row) Cells() []Cell {
contacted := r.Counts[StageContacted]
out := make([]Cell, len(Stages))
past := false
for i, s := range Stages {
c := Cell{Stage: s.ID, Count: r.Counts[s.ID]}
if past && contacted > 0 && c.Count > 0 && s.ID != StageVisited {
c.Rate = fmt.Sprintf("%.0f%%", 100*float64(c.Count)/float64(contacted))
}
if s.ID == StageContacted {
past = true
}
out[i] = c
}
return out
}
// Total is the number of events on the row.
func (r *Row) Total() int {
n := 0
for _, c := range r.Counts {
n += c
}
return n
}
// Filter narrows the scorecard.
type Filter struct {
Since time.Time // zero: all time
Channel string // "": all
}
// Scorecard counts each signal's funnel. A person counts once per stage
// however many events they have; aggregate events add their count.
func Scorecard(d *db.DB, f Filter) ([]Row, error) {
list, err := List(d)
if err != nil {
return nil, err
}
rows := make([]Row, 0, len(list)+1)
index := map[int64]int{}
for i := range list {
index[list[i].ID] = len(rows)
rows = append(rows, Row{Signal: &list[i], Counts: map[string]int{}})
}
index[0] = len(rows)
rows = append(rows, Row{Counts: map[string]int{}})
where, args := []string{"1 = 1"}, []any{}
if !f.Since.IsZero() {
where = append(where, "at >= ?")
args = append(args, formatTime(f.Since))
}
if f.Channel != "" {
where = append(where, "channel = ?")
args = append(args, f.Channel)
}
q, err := d.Query(`SELECT coalesce(signal_id, 0), stage,
count(DISTINCT CASE WHEN subject != '' THEN subject END) + sum(CASE WHEN subject = '' THEN count ELSE 0 END),
sum(CASE WHEN stage = 'paid' THEN value_cents ELSE 0 END)
FROM funnel_events WHERE `+strings.Join(where, " AND ")+` GROUP BY 1, 2`, args...)
if err != nil {
return nil, err
}
defer q.Close()
for q.Next() {
var sig, value int64
var stage string
var n int
if err := q.Scan(&sig, &stage, &n, &value); err != nil {
return nil, err
}
i, ok := index[sig]
if !ok {
i = index[0]
}
rows[i].Counts[stage] += n
rows[i].RevenueCents += value
}
if err := q.Err(); err != nil {
return nil, err
}
if f.Channel == "" || f.Channel == SourceOrigami || f.Channel == SourceExplee {
sq, err := d.Query(`SELECT coalesce(signal_id, 0), sum(spend_cents) FROM outside_campaigns
WHERE ? = '' OR source = ? GROUP BY 1`, f.Channel, f.Channel)
if err != nil {
return nil, err
}
defer sq.Close()
for sq.Next() {
var sig, spend int64
if err := sq.Scan(&sig, &spend); err != nil {
return nil, err
}
if i, ok := index[sig]; ok {
rows[i].SpendCents += spend
}
}
if err := sq.Err(); err != nil {
return nil, err
}
}
// The "no signal" row only when it has something.
if last := rows[len(rows)-1]; last.Total() == 0 && last.SpendCents == 0 {
rows = rows[:len(rows)-1]
}
return rows, nil
}