Files
supermarket/internal/web/prospects.go
T
davidandClaude Opus 5.5 c2772a7927 Phase 2 part 6: outreach by email and LinkedIn
Drafts are written by the AI from the person's buying signal (hypothesis
and angle), their company and their history, then reviewed and edited.
Queued emails go out through the Core's mail server one at a time, within
the sending hours, the daily limit and a gap, never to a suppressed or
bouncing address or someone emailed in the last 14 days; with a signature,
an opt-out line, UTM-tagged links and a copy in Sent. The inbox is read
read-only every 10 minutes: replies (by Message-ID or sender) count as
Replied, bounces mark the address, and "stop" replies are suppressed.
LinkedIn messages are copied, sent by hand and marked sent. New pages:
Prospects → Outreach and Settings → Email (with an SMTP, IMAP, SPF, DKIM
and DMARC check). Schema 10; emersion/go-imap for IMAP.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 06:09:47 -07:00

377 lines
11 KiB
Go

package web
import (
"errors"
"net/http"
"strconv"
"strings"
"time"
"supermarket/internal/crm"
"supermarket/internal/enrich"
"supermarket/internal/outreach"
"supermarket/internal/prospects"
"supermarket/internal/secrets"
"supermarket/internal/signals"
)
// newProspects is how many companies and people wait for review.
func (s *Server) newProspects() int {
counts, err := prospects.Counts(s.DB)
if err != nil {
s.Log.Error("counting prospects", "err", err)
}
return counts[prospects.StatusNew]
}
// reviewTab is the status a request asks for, new by default.
func reviewTab(v string) string {
for _, st := range prospects.Statuses {
if v == st {
return v
}
}
return prospects.StatusNew
}
func (s *Server) prospectsPage(w http.ResponseWriter, r *http.Request) {
sig, _ := strconv.ParseInt(r.URL.Query().Get("signal"), 10, 64)
s.renderProspects(w, r, reviewTab(r.URL.Query().Get("status")), sig, "")
}
// reviewURL is the review screen for a tab and a signal filter.
func reviewURL(tab string, signalID int64) string {
u := "/prospects?status=" + tab
if signalID != 0 {
u += "&signal=" + strconv.FormatInt(signalID, 10)
}
return u
}
func (s *Server) renderProspects(w http.ResponseWriter, r *http.Request, tab string, signalID int64, errMsg string) {
companies, loose, err := prospects.Review(s.DB, tab, signalID, 200)
if err != nil {
s.serverError(w, err)
return
}
counts, err := prospects.Counts(s.DB)
if err != nil {
s.serverError(w, err)
return
}
// Records already in the CRM that look like each prospect, from the
// last sync. Only worth showing before a decision.
matches := map[string][]crm.Record{}
if tab == prospects.StatusNew {
for i := range companies {
c := &companies[i]
if m, err := c.CRMMatches(s.DB); err == nil && len(m) > 0 {
matches["company:"+strconv.FormatInt(c.ID, 10)] = m
}
for j := range c.Contacts {
p := &c.Contacts[j]
if m, err := p.CRMMatches(s.DB); err == nil && len(m) > 0 {
matches["contact:"+strconv.FormatInt(p.ID, 10)] = m
}
}
}
for i := range loose {
if m, err := loose[i].CRMMatches(s.DB); err == nil && len(m) > 0 {
matches["contact:"+strconv.FormatInt(loose[i].ID, 10)] = m
}
}
}
sync, err := crm.LoadSync(s.DB)
if err != nil {
s.serverError(w, err)
return
}
list, err := signals.List(s.DB)
if err != nil {
s.serverError(w, err)
return
}
names := map[int64]string{}
for _, sg := range list {
names[sg.ID] = sg.Name
}
// Each prospect's funnel so far.
var subjects []string
for _, c := range companies {
subjects = append(subjects, prospects.Subject("company", c.ID))
for _, p := range c.Contacts {
subjects = append(subjects, prospects.Subject("contact", p.ID))
}
}
for _, p := range loose {
subjects = append(subjects, prospects.Subject("contact", p.ID))
}
evs, err := signals.SubjectEvents(s.DB, subjects...)
if err != nil {
s.serverError(w, err)
return
}
var contactIDs []int64
for _, c := range companies {
for _, p := range c.Contacts {
contactIDs = append(contactIDs, p.ID)
}
}
for _, p := range loose {
contactIDs = append(contactIDs, p.ID)
}
messages, err := outreach.ForContacts(s.DB, contactIDs)
if err != nil {
s.serverError(w, err)
return
}
runs, err := enrich.Latest(s.DB, subjects...)
if err != nil {
s.serverError(w, err)
return
}
events := map[string][]signals.Event{}
for _, e := range evs {
if e.Stage != signals.StageFound {
events[e.Subject] = append(events[e.Subject], e)
}
}
s.render(w, r, "prospects", page{Title: "Review prospects", Nav: "prospects/review", Error: errMsg, Data: map[string]any{
"Tab": tab,
"Statuses": prospects.Statuses,
"Counts": counts,
"Companies": companies,
"Loose": loose,
"Matches": matches,
"Synced": sync.Last,
"Signals": list,
"SignalNames": names,
"Signal": signalID,
"Events": events,
"Stages": signals.Stages[1:], // found is recorded on its own
"Channels": signals.Channels,
"Back": reviewURL(tab, signalID),
"Today": time.Now().Format("2006-01-02"),
"Hunter": s.Secrets.Has(secrets.HunterAPIKey),
"Runs": runs,
"Messages": messages,
"Unverified": len(unverified(companies, loose)),
"MaxVerify": maxVerify,
}})
}
// prospectAction handles the review screen's buttons.
func (s *Server) prospectAction(w http.ResponseWriter, r *http.Request) {
kind, action := r.PathValue("kind"), r.PathValue("action")
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil || (kind != "company" && kind != "contact") {
http.NotFound(w, r)
return
}
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
tab := reviewTab(r.PostFormValue("tab"))
filter, _ := strconv.ParseInt(r.PostFormValue("filter"), 10, 64)
now := time.Now()
var msg string
switch kind + "/" + action {
case "company/signal", "contact/signal":
sig, _ := strconv.ParseInt(r.PostFormValue("signal"), 10, 64)
err, msg = prospects.SetSignal(s.DB, kind, id, sig), "saved"
case "company/outcome", "contact/outcome":
err, msg = s.prospectOutcome(w, r, kind, id, tab), "outcome"
case "company/accept":
err, msg = ignore(prospects.AcceptCompany(s.DB, id, now)), "accepted"
case "company/accept-all":
err, msg = prospects.AcceptAll(s.DB, id, now), "accepted"
case "contact/accept":
err, msg = ignore(prospects.AcceptContact(s.DB, id, now)), "accepted"
case "company/reject":
err, msg = prospects.RejectCompany(s.DB, id, now), "rejected"
case "contact/reject":
err, msg = prospects.RejectContact(s.DB, id, now), "rejected"
case "company/people", "contact/find-email", "contact/verify":
err, msg = s.enrichAction(r, kind, action, id), "hunter-done"
if action == "verify" {
msg = "verified"
}
case "company/reconsider", "contact/reconsider":
err, msg = prospects.Reconsider(s.DB, kind, id), "reconsidered"
case "company/suppress":
c, gerr := prospects.GetCompany(s.DB, id)
if err = gerr; err == nil {
if c.Domain == "" {
err = errors.New(c.Name + " has no website, so there's no domain to suppress")
} else {
err = prospects.Suppress(s.DB, "domain", c.Domain, r.PostFormValue("reason"), now)
}
}
msg = "suppressed"
case "contact/suppress":
p, gerr := prospects.GetContact(s.DB, id)
if err = gerr; err == nil {
if p.Email == "" {
err = errors.New(p.Name() + " has no email address to suppress")
} else {
err = prospects.Suppress(s.DB, "email", p.Email, r.PostFormValue("reason"), now)
}
}
msg = "suppressed"
default:
http.NotFound(w, r)
return
}
if errors.Is(err, prospects.ErrNotFound) {
http.NotFound(w, r)
return
}
if err != nil {
s.renderProspects(w, r, tab, filter, "Couldn't do that: "+err.Error())
return
}
redirect(w, r, reviewURL(tab, filter), msg)
}
// ignore drops a result and keeps the error.
func ignore[T any](_ T, err error) error { return err }
// --- Adding by hand ---
type prospectFormData struct {
Signals []signals.Signal
Company prospects.Company
Contact prospects.Contact
CompanyID int64 // adding a person at a company already in review
Companies []prospects.Company
For string // that company's name
}
func (s *Server) prospectForm(w http.ResponseWriter, r *http.Request) {
d := prospectFormData{}
d.Signals, _ = signals.List(s.DB)
d.Company.SignalID, _ = strconv.ParseInt(r.URL.Query().Get("signal"), 10, 64)
if id, err := strconv.ParseInt(r.URL.Query().Get("company"), 10, 64); err == nil {
c, err := prospects.GetCompany(s.DB, id)
if err != nil {
http.NotFound(w, r)
return
}
d.CompanyID, d.For = c.ID, c.Name
}
s.render(w, r, "prospect-new", page{Title: "Add a prospect", Nav: "prospects/review", Data: d})
}
func (s *Server) prospectAdd(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
f := r.PostFormValue
now := time.Now()
d := prospectFormData{
Company: prospects.Company{
Name: f("company_name"), Website: f("website"), LinkedIn: f("company_linkedin"),
Industry: f("industry"), Size: f("size"), Location: f("location"), Why: f("why"),
Source: prospects.SourceManual, SourceDetail: f("source_detail"),
},
Contact: prospects.Contact{
FirstName: f("first_name"), LastName: f("last_name"), Title: f("title"), Email: f("email"),
LinkedIn: f("linkedin"), Phone: f("phone"),
Source: prospects.SourceManual, SourceDetail: f("source_detail"),
},
}
d.CompanyID, _ = strconv.ParseInt(f("company_id"), 10, 64)
d.Signals, _ = signals.List(s.DB)
d.Company.SignalID, _ = strconv.ParseInt(f("signal"), 10, 64)
d.Contact.SignalID = d.Company.SignalID
if d.CompanyID != 0 {
c, err := prospects.GetCompany(s.DB, d.CompanyID)
if err != nil {
http.NotFound(w, r)
return
}
d.For = c.Name
}
fail := func(msg string) {
s.render(w, r, "prospect-new", page{Title: "Add a prospect", Nav: "prospects/review", Error: msg, Data: d})
}
hasCompany := strings.TrimSpace(d.Company.Name) != "" || strings.TrimSpace(d.Company.Website) != ""
hasPerson := strings.TrimSpace(d.Contact.FirstName+d.Contact.LastName+d.Contact.Email) != ""
if !hasCompany && !hasPerson && d.CompanyID == 0 {
fail("Give a company, a person, or both.")
return
}
if d.CompanyID == 0 && hasCompany {
if strings.TrimSpace(d.Company.Name) == "" {
fail("Give the company's name.")
return
}
id, _, err := prospects.AddCompany(s.DB, d.Company, now)
if err != nil {
fail(addError(err))
return
}
d.CompanyID = id
}
if hasPerson {
d.Contact.CompanyID = d.CompanyID
if _, _, err := prospects.AddContact(s.DB, d.Contact, now); err != nil {
fail(addError(err))
return
}
} else if d.CompanyID != 0 && !hasCompany {
fail("Give the person's name or email.")
return
}
redirect(w, r, "/prospects", "prospect-added")
}
func addError(err error) string {
if errors.Is(err, prospects.ErrSuppressed) {
return "That's on your suppression list (" + strings.TrimSuffix(err.Error(), ": "+prospects.ErrSuppressed.Error()) +
"), so it can't be added. Take it off the list first if that's a mistake."
}
return err.Error()
}
// --- Suppression list ---
func (s *Server) suppressedPage(w http.ResponseWriter, r *http.Request) {
s.renderSuppressed(w, r, "", "")
}
func (s *Server) renderSuppressed(w http.ResponseWriter, r *http.Request, value, errMsg string) {
list, err := prospects.Suppressions(s.DB)
if err != nil {
s.serverError(w, err)
return
}
s.render(w, r, "suppressed", page{Title: "Suppression list", Nav: "prospects/suppressed", Error: errMsg, Data: map[string]any{
"List": list,
"Value": value,
}})
}
func (s *Server) suppressedAction(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
value := r.PostFormValue("value")
if r.PostFormValue("remove") != "" {
if err := prospects.Unsuppress(s.DB, r.PostFormValue("kind"), value); err != nil {
s.renderSuppressed(w, r, "", err.Error())
return
}
redirect(w, r, "/prospects/suppressed", "unsuppressed")
return
}
if err := prospects.Suppress(s.DB, "", value, r.PostFormValue("reason"), time.Now()); err != nil {
s.renderSuppressed(w, r, value, err.Error())
return
}
redirect(w, r, "/prospects/suppressed", "suppressed")
}