Phase 2 part 7: the end of the funnel

Posts can be written for a buying signal: the prompt gets its hypothesis
and angle, and links carry its campaign tag. Plausible (Stats API v2) is
read once a day for visitors on tagged links, recorded per signal as
Visited. Stripe (restricted key) is read every hour: $0 checkouts are
Signed up, paid invoices and one-time payments are Paid with their value,
tied to a signal by the checkout's utm_campaign metadata or the payer's
email. The Core's Cal.com has no API, so booking emails from Cal.com in
the outreach mailbox count as Booked. New Settings → Website & sales;
the signal page lists its posts and tagged links. Schema 11.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-22 06:42:03 -07:00
co-authored by Claude Opus 5.5
parent 90d73cf907
commit d23d5e2a87
32 changed files with 1775 additions and 26 deletions
+108 -11
View File
@@ -21,6 +21,7 @@ import (
"supermarket/internal/db"
"supermarket/internal/prospects"
"supermarket/internal/signals"
)
// imapClient connects and signs in to the mailbox.
@@ -109,6 +110,7 @@ type Check struct {
Stops int `json:"stops"`
Bounces int `json:"bounces"`
AutoReplies int `json:"auto_replies"`
Bookings int `json:"bookings"`
Error string `json:"error,omitempty"`
}
@@ -170,8 +172,19 @@ func checkReplies(ctx context.Context, d *db.DB, s Settings, password string, no
if err != nil {
return err
}
if !first.Valid {
// Nothing sent yet: start from here, without reading older mail.
var since time.Time
if first.Valid {
since, _ = time.Parse(timeFormat, first.String)
since = since.AddDate(0, 0, -1)
}
if s.BookingFrom != "" {
if b := now.AddDate(0, 0, -bookingDays); since.IsZero() || b.Before(since) {
since = b
}
}
if since.IsZero() {
// Nothing sent yet and no bookings to look for: start from here,
// without reading older mail.
return d.PutJSON(stateKey, inboxState{UIDValidity: mbox.UidValidity, LastUID: mbox.UidNext - 1})
}
criteria := imap.NewSearchCriteria()
@@ -179,8 +192,7 @@ func checkReplies(ctx context.Context, d *db.DB, s Settings, password string, no
criteria.Uid = new(imap.SeqSet)
criteria.Uid.AddRange(state.LastUID+1, 0)
} else {
since, _ := time.Parse(timeFormat, first.String)
criteria.Since = since.AddDate(0, 0, -1)
criteria.Since = since
}
uids, err := c.UidSearch(criteria)
if err != nil {
@@ -202,7 +214,7 @@ func checkReplies(ctx context.Context, d *db.DB, s Settings, password string, no
}
for start := 0; start < len(fresh); start += 100 {
batch := fresh[start:min(start+100, len(fresh))]
if err := readBatch(c, d, batch, res); err != nil {
if err := readBatch(c, d, s, batch, res); err != nil {
return err
}
last = max(last, batch[len(batch)-1])
@@ -243,16 +255,19 @@ var fullSection = &imap.BodySectionName{Peek: true}
// found is a message that answers, or bounces, one of ours.
type found struct {
uid uint32
msg *Message
bounce bool
id string // its Message-ID
date time.Time
uid uint32
booking bool
subject string
skip []string // addresses that aren't the attendee: ours, Cal.com's
msg *Message
bounce bool
id string // its Message-ID
date time.Time
}
// readBatch looks at the headers of some new messages, then reads the ones
// that concern outreach.
func readBatch(c *client.Client, d *db.DB, uids []uint32, res *Check) error {
func readBatch(c *client.Client, d *db.DB, s Settings, uids []uint32, res *Check) error {
set := new(imap.SeqSet)
set.AddNum(uids...)
ch := make(chan *imap.Message, len(uids))
@@ -275,6 +290,17 @@ func readBatch(c *client.Client, d *db.DB, uids []uint32, res *Check) error {
if len(m.Envelope.From) > 0 {
fromAddr = strings.ToLower(m.Envelope.From[0].Address())
}
if s.BookingFrom != "" && fromAddr == strings.ToLower(s.BookingFrom) {
skip := []string{fromAddr, strings.ToLower(s.FromAddress), strings.ToLower(s.Username)}
for _, a := range m.Envelope.To {
skip = append(skip, strings.ToLower(a.Address()))
}
if m.Size < 5<<20 {
todo = append(todo, found{uid: m.Uid, booking: true, subject: m.Envelope.Subject, skip: skip,
id: m.Envelope.MessageId, date: m.Envelope.Date})
}
continue
}
if isBounce(fromAddr, h.Get("Content-Type")) {
if m.Size < 5<<20 {
todo = append(todo, found{uid: m.Uid, bounce: true, id: m.Envelope.MessageId, date: m.Envelope.Date})
@@ -301,6 +327,12 @@ func readBatch(c *client.Client, d *db.DB, uids []uint32, res *Check) error {
if err != nil {
return err
}
if f.booking {
if err := booked(d, f, raw, res); err != nil {
return err
}
continue
}
if f.bounce {
if err := bounced(d, raw, res); err != nil {
return err
@@ -517,3 +549,68 @@ func WantsStop(reply string) bool {
first, _, _ := strings.Cut(reply, "\n")
return stopAlone.MatchString(strings.TrimSpace(first)) || stopPhrases.MatchString(reply)
}
// bookingDays is how far back bookings are looked for the first time.
const bookingDays = 30
var (
emailRe = regexp.MustCompile(`[A-Za-z0-9._%+'-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}`)
notNewBooking = regexp.MustCompile(`(?i)cancel|reschedul|declined|rejected|reminder|request`)
)
// booked records a Cal.com booking notice as a Booked step for the person
// who booked: the first address in it that isn't ours or Cal.com's. Notices
// of cancellations, reschedules and reminders are skipped.
func booked(d *db.DB, f found, raw []byte, res *Check) error {
if notNewBooking.MatchString(f.subject) {
return nil
}
text := plainText(raw)
attendee := ""
for _, a := range emailRe.FindAllString(text, -1) {
a = strings.ToLower(strings.Trim(a, ".'"))
local, _, _ := strings.Cut(a, "@")
if local == "noreply" || local == "no-reply" || local == "notifications" || contains(f.skip, a) {
continue
}
attendee = a
break
}
if attendee == "" {
return nil
}
at := f.date
if at.IsZero() {
at = time.Now()
}
ev := signals.Event{Stage: signals.StageBooked, Channel: "website", Email: attendee, Source: signals.SourceSupermarket,
ExternalID: "booking:" + f.id, Note: truncate(strings.TrimSpace(f.subject), 200), At: at}
if f.id == "" {
ev.ExternalID = "booking:" + attendee + ":" + at.UTC().Format("2006-01-02T15")
}
var id, sig int64
if err := d.QueryRow(`SELECT p.id, coalesce(p.signal_id, c.signal_id, 0) FROM prospect_contacts p
LEFT JOIN prospect_companies c ON c.id = p.company_id WHERE p.email = ? LIMIT 1`, attendee).Scan(&id, &sig); err == nil {
ev.Subject, ev.SignalID = prospects.Subject("contact", id), sig
var ch string
if d.QueryRow(`SELECT channel FROM outreach WHERE contact_id = ? AND status = 'sent' ORDER BY sent_at DESC LIMIT 1`, id).Scan(&ch) == nil {
ev.Channel = ch
}
} else {
ev.Subject = "booking:" + attendee
}
added, err := signals.Record(d, ev)
if added {
res.Bookings++
}
return err
}
func contains(list []string, v string) bool {
for _, x := range list {
if x == v {
return true
}
}
return false
}