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
}
+40
View File
@@ -534,3 +534,43 @@ func TestSettings(t *testing.T) {
t.Errorf("dns: %+v", c)
}
}
func TestBookings(t *testing.T) {
d := openDB(t)
s := imapServer(t)
s.BookingFrom = "calcom@example.com"
ctx := context.Background()
ann := person(t, d, "Ann", "ann@acme.example")
deliver(t, s, "From: Cal.com <calcom@example.com>\nTo: Pat Lee <pat@example.com>\nSubject: New event: 30 min between Pat Lee and Ann Doe\n"+
"Message-ID: <b1@cal>\nContent-Type: text/plain\n\nWhat: 30 min\nWho: Pat Lee - Organizer pat@example.com\nAnn Doe ann@acme.example\n")
deliver(t, s, "From: Cal.com <calcom@example.com>\nTo: pat@example.com\nSubject: Event cancelled: 30 min with Ann Doe\n"+
"Message-ID: <b2@cal>\n\nCancelled. ann@acme.example\n")
deliver(t, s, "From: Cal.com <calcom@example.com>\nTo: pat@example.com\nSubject: New event: Intro between Pat Lee and Zed\n"+
"Message-ID: <b3@cal>\nContent-Type: text/html\n\n<p>Who: <a href=\"mailto:noreply@cal.example\">x</a> zed@else.example</p>\n")
res, err := CheckReplies(ctx, d, s, "password", now)
if err != nil {
t.Fatal(err)
}
if res.Bookings != 2 {
t.Fatalf("check: %+v", res)
}
evs, _ := signals.SubjectEvents(d, prospects.Subject("contact", ann))
var booked *signals.Event
for i := range evs {
if evs[i].Stage == signals.StageBooked {
booked = &evs[i]
}
}
if booked == nil || booked.SignalID == 0 || booked.Email != "ann@acme.example" || !strings.Contains(booked.Note, "30 min") {
t.Errorf("ann's booking: %+v", evs)
}
if zed, _ := signals.SubjectEvents(d, "booking:zed@else.example"); len(zed) != 1 || zed[0].SignalID != 0 {
t.Errorf("zed's booking: %+v", zed)
}
// Read again: nothing new.
if res, _ := CheckReplies(ctx, d, s, "password", now); res.Bookings != 0 {
t.Errorf("again: %+v", res)
}
}
+7 -2
View File
@@ -36,6 +36,9 @@ type Settings struct {
SchedulingLink string `json:"scheduling_link"` // offered as the next step, if set
SaveToSent bool `json:"save_to_sent"` // put a copy in the mailbox's Sent folder
ReadReplies bool `json:"read_replies"`
// BookingFrom is the address Cal.com sends booking notices from; its
// emails in the inbox count as bookings.
BookingFrom string `json:"booking_from"`
// Insecure allows a mail server without TLS. Only tests set it.
Insecure bool `json:"-"`
@@ -94,13 +97,15 @@ func Save(d *db.DB, s Settings) error {
// Check finds settings that can't work.
func (s *Settings) Check() error {
for _, f := range []*string{&s.SMTPHost, &s.IMAPHost, &s.Username, &s.FromName, &s.FromAddress, &s.SchedulingLink} {
for _, f := range []*string{&s.SMTPHost, &s.IMAPHost, &s.Username, &s.FromName, &s.FromAddress, &s.SchedulingLink, &s.BookingFrom} {
*f = strings.TrimSpace(*f)
}
s.FromAddress = strings.ToLower(s.FromAddress)
s.FromAddress, s.BookingFrom = strings.ToLower(s.FromAddress), strings.ToLower(s.BookingFrom)
switch {
case s.FromAddress != "" && !strings.Contains(s.FromAddress, "@"):
return errors.New("the From address isn't an email address")
case s.BookingFrom != "" && !strings.Contains(s.BookingFrom, "@"):
return errors.New("Cal.com's sending address isn't an email address")
case s.SMTPPort < 1 || s.SMTPPort > 65535 || s.IMAPPort < 1 || s.IMAPPort > 65535:
return errors.New("a port must be between 1 and 65535")
case s.DailyLimit < 1 || s.DailyLimit > 200: