package outreach import ( "bytes" "context" "errors" "io" "mime/quotedprintable" "net" "net/textproto" "path/filepath" "strconv" "strings" "sync" "testing" "time" "github.com/emersion/go-imap/backend/memory" imapclient "github.com/emersion/go-imap/client" "github.com/emersion/go-imap/server" "supermarket/internal/ai" "supermarket/internal/core" "supermarket/internal/db" "supermarket/internal/profile" "supermarket/internal/prospects" "supermarket/internal/signals" "supermarket/internal/utm" ) // A Wednesday, mid-morning local time. var now = time.Date(2026, 11, 25, 10, 0, 0, 0, time.Local) func openDB(t *testing.T) *db.DB { t.Helper() d, err := db.Open(filepath.Join(t.TempDir(), "app.db")) if err != nil { t.Fatal(err) } t.Cleanup(func() { d.Close() }) return d } var prof = &profile.Profile{Name: "Federated Computer", Description: "Open-source business apps, run for you.", Websites: []profile.Website{{URL: "https://federated.computer"}}} func settings() Settings { s := Defaults(&core.Core{Domain: "example.com", Email: "pat@example.com", Name: "Pat Lee"}, prof) return s } // person adds an accepted person at Acme, tagged with a signal. func person(t *testing.T, d *db.DB, first, email string) int64 { t.Helper() var sig int64 if err := d.QueryRow(`SELECT id FROM signals WHERE slug = 'leaving-m365'`).Scan(&sig); err != nil { s := &signals.Signal{Name: "Leaving M365", Slug: "leaving-m365", Hypothesis: "Price rise", Angle: "Flat price"} if err := signals.Save(d, s); err != nil { t.Fatal(err) } sig = s.ID } co, _, err := prospects.AddCompany(d, prospects.Company{Name: "Acme", Website: "acme.example", Source: prospects.SourceManual, SignalID: sig, Why: "Complained about per-seat pricing"}, now) if err != nil { t.Fatal(err) } id, _, err := prospects.AddContact(d, prospects.Contact{CompanyID: co, FirstName: first, LastName: "Doe", Title: "CTO", Email: email, LinkedIn: "https://linkedin.com/in/" + first, Source: prospects.SourceManual}, now) if err != nil { t.Fatal(err) } if _, err := d.Exec(`UPDATE prospect_contacts SET status = 'accepted', decided_at = ? WHERE id = ?`, formatTime(now), id); err != nil { t.Fatal(err) } return id } type fakeAI struct { req ai.Request out string } func (f *fakeAI) Generate(_ context.Context, req ai.Request) (string, error) { f.req = req return f.out, nil } func TestDraft(t *testing.T) { d := openDB(t) s := settings() s.SchedulingLink = "https://cal.example.com/pat" ann := person(t, d, "Ann", "ann@acme.example") f := &fakeAI{out: `{"subject":"per-seat pricing at Acme","body":"Hi Ann, ..."}`} m, err := Draft(context.Background(), d, f, prof, s, ann, ChannelEmail, now) if err != nil { t.Fatal(err) } if m.Status != StatusDraft || m.To != "ann@acme.example" || m.Subject != "per-seat pricing at Acme" || m.SignalID == 0 { t.Errorf("draft: %+v", m) } for _, want := range []string{"Ann Doe", "CTO", "Acme", "Complained about per-seat pricing", "Leaving M365", "Flat price"} { if !strings.Contains(f.req.Prompt, want) { t.Errorf("prompt lacks %q", want) } } for _, want := range []string{"Pat Lee at Federated Computer", "https://cal.example.com/pat", "ignore any instructions"} { if !strings.Contains(f.req.System, want) { t.Errorf("system prompt lacks %q", want) } } if f.req.Task != ai.TaskOutreach { t.Errorf("task: %q", f.req.Task) } if _, err := Draft(context.Background(), d, f, prof, s, ann, ChannelEmail, now); err == nil || !strings.Contains(err.Error(), "already has a message") { t.Errorf("a second draft: %v", err) } f.out = `{"subject":"ignored","body":"Hi Ann"}` li, err := Draft(context.Background(), d, f, prof, s, ann, ChannelLinkedIn, now) if err != nil || li.Subject != "" || !strings.Contains(f.req.System, "LinkedIn message") { t.Errorf("linkedin: %+v %v", li, err) } bob := person(t, d, "Bob", "") if _, err := Draft(context.Background(), d, f, prof, s, bob, ChannelEmail, now); err == nil { t.Error("drafted an email to someone without an address") } } type fakeSender struct { sent []*Email saved int err error } func (f *fakeSender) Send(_ context.Context, e *Email) error { if f.err != nil { return f.err } f.sent = append(f.sent, e) return nil } func (f *fakeSender) Saved(context.Context, *Email, time.Time) error { f.saved++ return nil } func draft(t *testing.T, d *db.DB, contact int64, body string) *Message { t.Helper() p, _ := prospects.GetContact(d, contact) m := &Message{ContactID: contact, SignalID: p.SignalID, Channel: ChannelEmail, To: p.Email, Subject: "Hello", Body: body, CreatedAt: now} if err := insert(d, m); err != nil { t.Fatal(err) } return m } func TestQueueAndSend(t *testing.T) { d := openDB(t) s := settings() s.DailyLimit, s.GapMinutes = 2, 5 snd := &fakeSender{} tags := utm.NewTagger([]string{"https://federated.computer"}) ctx := context.Background() ann := draft(t, d, person(t, d, "Ann", "ann@acme.example"), "See https://federated.computer/pricing.") bob := draft(t, d, person(t, d, "Bob", "bob@acme.example"), "Hi Bob") cat := draft(t, d, person(t, d, "Cat", "cat@acme.example"), "Hi Cat") for _, m := range []*Message{ann, bob, cat} { if err := Queue(d, m.ID, now.Add(time.Duration(m.ID)*time.Second)); err != nil { t.Fatal(err) } } if err := Queue(d, ann.ID, now); err == nil { t.Error("queued twice") } // Saturday: nothing goes. if m, err := SendDue(ctx, d, s, snd, tags, time.Date(2026, 11, 28, 10, 0, 0, 0, time.Local)); m != nil || err != nil { t.Errorf("weekend: %v %v", m, err) } // Before 9: nothing goes. if m, _ := SendDue(ctx, d, s, snd, tags, now.Add(-2*time.Hour)); m != nil { t.Error("sent before hours") } m, err := SendDue(ctx, d, s, snd, tags, now) if err != nil || m == nil || m.ID != ann.ID || len(snd.sent) != 1 || snd.saved != 1 { t.Fatalf("first: %+v %v", m, err) } raw := decoded(snd.sent[0].Raw) for _, want := range []string{"To: \"Ann Doe\" ", "From: \"Pat Lee\" ", "Message-ID: "} { if !strings.Contains(raw, want) { t.Errorf("email lacks %q:\n%s", want, raw) } } // The gap holds the next one back. if m, _ := SendDue(ctx, d, s, snd, tags, now.Add(2*time.Minute)); m != nil { t.Error("sent inside the gap") } if m, _ := SendDue(ctx, d, s, snd, tags, now.Add(6*time.Minute)); m == nil || m.ID != bob.ID { t.Errorf("second: %+v", m) } // The daily limit holds; Send now too. if m, _ := SendDue(ctx, d, s, snd, tags, now.Add(20*time.Minute)); m != nil { t.Error("sent over the limit") } if err := SendNow(ctx, d, s, snd, tags, cat.ID, now.Add(21*time.Minute)); err == nil || !strings.Contains(err.Error(), "limit of 2") { t.Errorf("send now over the limit: %v", err) } // Tomorrow it goes. if m, _ := SendDue(ctx, d, s, snd, tags, now.Add(24*time.Hour)); m == nil || m.ID != cat.ID { t.Errorf("tomorrow: %+v", m) } got, _ := Get(d, ann.ID) if got.Status != StatusSent || got.MessageID == "" || got.SentAt.IsZero() { t.Errorf("ann: %+v", got) } evs, _ := signals.SubjectEvents(d, prospects.Subject("contact", ann.ContactID)) if len(evs) != 1 || evs[0].Stage != signals.StageContacted || evs[0].Channel != "email" || evs[0].SignalID == 0 { t.Errorf("events: %+v", evs) } // No second email to the same address within two weeks, and none to a // suppressed one; a failed send is kept with its reason. again := draft(t, d, ann.ContactID, "Again") if err := Queue(d, again.ID, now); err == nil || !strings.Contains(err.Error(), "already emailed") { t.Errorf("repeat: %v", err) } dan := draft(t, d, person(t, d, "Dan", "dan@acme.example"), "Hi Dan") Queue(d, dan.ID, now) prospects.Suppress(d, "email", "dan@acme.example", "", now) if err := SendNow(ctx, d, s, snd, tags, dan.ID, now.Add(48*time.Hour)); !errors.Is(err, prospects.ErrSuppressed) { t.Errorf("suppressed: %v", err) } if got, _ := Get(d, dan.ID); got.Status != StatusFailed || !strings.Contains(got.Error, "suppression") { t.Errorf("dan: %+v", got) } eve := draft(t, d, person(t, d, "Eve", "eve@acme.example"), "Hi Eve") Queue(d, eve.ID, now) snd.err = errors.New("550 mailbox unavailable") if err := SendNow(ctx, d, s, snd, tags, eve.ID, now.Add(48*time.Hour)); err == nil { t.Error("no error from a failed send") } if got, _ := Get(d, eve.ID); got.Status != StatusFailed || got.Error != "550 mailbox unavailable" { t.Errorf("eve: %+v", got) } // It can be queued again. if err := Queue(d, eve.ID, now); err != nil { t.Errorf("requeue: %v", err) } counts, _ := Counts(d) if counts[StatusSent] != 3 || counts[StatusFailed] != 1 || counts[StatusQueued] != 1 || counts[StatusDraft] != 1 { t.Errorf("counts: %v", counts) } } func decoded(raw []byte) string { head, body, _ := strings.Cut(string(raw), "\r\n\r\n") b, _ := io.ReadAll(quotedprintable.NewReader(strings.NewReader(body))) return head + "\r\n\r\n" + string(b) } func TestLinkedInByHand(t *testing.T) { d := openDB(t) id := person(t, d, "Ann", "") m := &Message{ContactID: id, Channel: ChannelLinkedIn, Body: "Hi Ann", CreatedAt: now} insert(d, m) if err := Queue(d, m.ID, now); err == nil { t.Error("queued a LinkedIn message") } if err := MarkSent(d, m.ID, "Hi Ann, edited", now); err != nil { t.Fatal(err) } if err := MarkReplied(d, m.ID, "Sounds interesting", "", now.Add(time.Hour)); err != nil { t.Fatal(err) } got, _ := Get(d, m.ID) if got.Body != "Hi Ann, edited" || got.Status != StatusSent || got.Reply != "Sounds interesting" { t.Errorf("linkedin: %+v", got) } evs, _ := signals.SubjectEvents(d, prospects.Subject("contact", id)) if len(evs) != 2 || evs[0].Channel != "linkedin" { t.Errorf("events: %+v", evs) } if replies, _ := List(d, "replied", 10); len(replies) != 1 { t.Errorf("replies tab: %+v", replies) } } // fakeSMTP is just enough of a mail server for net/smtp. func fakeSMTP(t *testing.T) (addr string, got func() string) { ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatal(err) } t.Cleanup(func() { ln.Close() }) var mu sync.Mutex var data bytes.Buffer go func() { for { conn, err := ln.Accept() if err != nil { return } go func(conn net.Conn) { defer conn.Close() tp := textproto.NewConn(conn) tp.PrintfLine("220 fake ESMTP") for { line, err := tp.ReadLine() if err != nil { return } cmd := strings.ToUpper(strings.Fields(line + " x")[0]) switch cmd { case "EHLO": tp.PrintfLine("250-fake\r\n250 AUTH PLAIN") case "AUTH": tp.PrintfLine("235 ok") case "DATA": tp.PrintfLine("354 go") b, _ := tp.ReadDotBytes() mu.Lock() data.Write(b) mu.Unlock() tp.PrintfLine("250 queued") case "QUIT": tp.PrintfLine("221 bye") return default: tp.PrintfLine("250 ok") } } }(conn) } }() return ln.Addr().String(), func() string { mu.Lock(); defer mu.Unlock(); return data.String() } } func TestSMTP(t *testing.T) { addr, got := fakeSMTP(t) host, port, _ := net.SplitHostPort(addr) s := settings() s.SMTPHost, s.Insecure = host, true s.SMTPPort, _ = strconv.Atoi(port) if err := CheckSMTP(context.Background(), s, "pw"); err != nil { t.Fatal(err) } if err := SendTest(context.Background(), s, Mailbox{Settings: s, Password: "pw"}, now); err != nil { t.Fatal(err) } if !strings.Contains(got(), "Subject: Supermarket test email") { t.Errorf("sent: %q", got()) } s.Insecure = false if err := CheckSMTP(context.Background(), s, "pw"); err == nil || !strings.Contains(err.Error(), "STARTTLS") { t.Errorf("no TLS: %v", err) } } // imapServer is an in-memory mailbox: user "username", password "password". func imapServer(t *testing.T) Settings { be := memory.New() srv := server.New(be) srv.AllowInsecureAuth = true ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatal(err) } go srv.Serve(ln) t.Cleanup(func() { srv.Close() }) host, port, _ := net.SplitHostPort(ln.Addr().String()) s := settings() s.IMAPHost, s.Username, s.Insecure = host, "username", true s.IMAPPort, _ = strconv.Atoi(port) return s } func deliver(t *testing.T, s Settings, raw string) { t.Helper() c, err := imapclient.Dial(net.JoinHostPort(s.IMAPHost, strconv.Itoa(s.IMAPPort))) if err != nil { t.Fatal(err) } defer c.Logout() if err := c.Login("username", "password"); err != nil { t.Fatal(err) } raw = strings.ReplaceAll(raw, "\n", "\r\n") if err := c.Append("INBOX", nil, now, bytes.NewBufferString(raw)); err != nil { t.Fatal(err) } } func TestCheckReplies(t *testing.T) { d := openDB(t) s := imapServer(t) ctx := context.Background() // Nothing sent yet: the inbox's old mail is skipped. if res, err := CheckReplies(ctx, d, s, "password", now); err != nil || res.Read != 0 { t.Fatalf("first check: %+v %v", res, err) } snd := &fakeSender{} sent := map[string]*Message{} for _, name := range []string{"ann", "bob", "cat", "dan", "eve"} { m := draft(t, d, person(t, d, name, name+"@acme.example"), "Hi") Queue(d, m.ID, now) if err := SendNow(ctx, d, Settings{DailyLimit: 10, FromAddress: "pat@example.com"}, snd, nil, m.ID, now); err != nil { t.Fatal(err) } sent[name], _ = Get(d, m.ID) } deliver(t, s, "From: Ann Doe \nTo: pat@example.com\nSubject: Re: Hello\nMessage-ID: \n"+ "In-Reply-To: "+sent["ann"].MessageID+"\nContent-Type: text/plain\n\nYes, let's talk next week.\n\nOn Tue, Pat wrote:\n> Hi\n") deliver(t, s, "From: bob@acme.example\nTo: pat@example.com\nSubject: question\nMessage-ID: \n\nWho are you?\n") deliver(t, s, "From: cat@acme.example\nTo: pat@example.com\nSubject: Out of office\nAuto-Submitted: auto-replied\nMessage-ID: \n\nAway.\n") deliver(t, s, "From: Mail Delivery System \nTo: pat@example.com\nSubject: Undelivered\n"+ "Message-ID: \nContent-Type: multipart/report; report-type=delivery-status; boundary=b\n\n--b\nContent-Type: text/plain\n\n"+ "Could not deliver.\n--b\nContent-Type: message/delivery-status\n\nStatus: 5.1.1\nDiagnostic-Code: smtp; 550 5.1.1 no such user\n--b\n"+ "Content-Type: text/rfc822-headers\n\nMessage-ID: "+sent["dan"].MessageID+"\n--b--\n") deliver(t, s, "From: eve@acme.example\nTo: pat@example.com\nSubject: Re: Hello\nMessage-ID: \nReferences: "+sent["eve"].MessageID+ "\nContent-Type: text/html\n\n

Please remove me from your list.

\n") deliver(t, s, "From: stranger@else.example\nTo: pat@example.com\nSubject: hi\nMessage-ID: \n\nunrelated\n") res, err := CheckReplies(ctx, d, s, "password", now.Add(time.Hour)) if err != nil { t.Fatal(err) } if res.Read != 6 || res.Replies != 3 || res.AutoReplies != 1 || res.Bounces != 1 || res.Stops != 1 { t.Fatalf("check: %+v", res) } ann, _ := Get(d, sent["ann"].ID) if ann.Reply != "Yes, let's talk next week." || ann.RepliedAt.IsZero() { t.Errorf("ann: %q", ann.Reply) } if bob, _ := Get(d, sent["bob"].ID); bob.Reply != "Who are you?" { t.Errorf("bob (matched by address): %q", bob.Reply) } if cat, _ := Get(d, sent["cat"].ID); !cat.RepliedAt.IsZero() { t.Error("an auto-reply counted as a reply") } dan, _ := Get(d, sent["dan"].ID) if dan.Status != StatusBounced || !strings.Contains(dan.Error, "550 5.1.1 no such user") { t.Errorf("dan: %+v", dan) } if p, _ := prospects.GetContact(d, dan.ContactID); p.EmailStatus != prospects.EmailInvalid { t.Errorf("dan's address: %q", p.EmailStatus) } if sup, _ := prospects.IsSuppressed(d, "eve@acme.example", ""); !sup { t.Error("eve asked to stop but isn't suppressed") } evs, _ := signals.SubjectEvents(d, prospects.Subject("contact", ann.ContactID)) var replyEv *signals.Event for i := range evs { if evs[i].Stage == signals.StageReplied { replyEv = &evs[i] } } if len(evs) != 2 || replyEv == nil || replyEv.Note != "Yes, let's talk next week." { t.Errorf("ann's events: %+v", evs) } // The next check reads only what's new. deliver(t, s, "From: ann@acme.example\nTo: pat@example.com\nSubject: Re: Hello\nMessage-ID: \n\nAlso, Tuesday works.\n") res, err = CheckReplies(ctx, d, s, "password", now.Add(2*time.Hour)) if err != nil || res.Read != 1 || res.Replies != 0 { t.Errorf("second check: %+v %v", res, err) } if last, _ := LastCheck(d); last == nil || last.Read != 1 { t.Errorf("last check: %+v", last) } if n, err := CheckIMAP(ctx, s, "password"); err != nil || n != 8 { t.Errorf("test: %d %v", n, err) } if _, err := CheckIMAP(ctx, s, "wrong"); err == nil { t.Error("a wrong password worked") } } func TestWantsStop(t *testing.T) { for reply, want := range map[string]bool{ "STOP": true, "Unsubscribe.": true, "remove me": true, "Please take me off your list": true, "Don't email me again": true, "We can't stop growing, let's talk": false, "Not interested, thanks": false, "Sure, send more info": false, } { if WantsStop(reply) != want { t.Errorf("%q: want %v", reply, want) } } } func TestSettings(t *testing.T) { d := openDB(t) s, ok, err := Load(d, &core.Core{Domain: "example.com", Email: "pat@example.com", Name: "Pat"}, prof) if err != nil || ok || s.SMTPHost != "mail.example.com" || s.Username != "pat@example.com" || !strings.Contains(s.Footer, "https://federated.computer") { t.Fatalf("defaults: %+v %v %v", s, ok, err) } if err := s.Ready(""); err == nil { t.Error("ready without a password") } s.StartHour, s.EndHour = 17, 9 if err := Save(d, s); err == nil { t.Error("saved hours that end before they start") } s.StartHour, s.EndHour, s.DailyLimit = 8, 18, 30 if err := Save(d, s); err != nil { t.Fatal(err) } if got, ok, _ := Load(d, nil, nil); !ok || got.DailyLimit != 30 || got.SMTPHost != "mail.example.com" { t.Errorf("loaded: %+v", got) } lookupTXT = func(_ context.Context, name string) ([]string, error) { switch name { case "example.com": return []string{"google-site-verification=x", "v=spf1 mx -all"}, nil case "dkim._domainkey.example.com": return []string{"k=rsa; p=MIGf"}, nil } return nil, errors.New("no such host") } defer func() { lookupTXT = net.DefaultResolver.LookupTXT }() c := CheckDNS(context.Background(), "example.com") if c.SPF != "v=spf1 mx -all" || c.DMARC != "" || c.DKIMSelector != "dkim" { t.Errorf("dns: %+v", c) } }