Phase 2 part 5: find people and verify emails with Hunter.io

Review gets Find people (Domain Search by the departments, seniority and
count set in Settings → Lead sources), Find their email (Email Finder for
a named person at a company), and Verify (one, or every unchecked address
in New). Every call is kept in enrich_runs (schema 9) with its result and
credits, and shown on the card. Nothing runs on a schedule. Sources are
shown by name (Hunter.io, origami.chat, explee.com).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-22 05:53:52 -07:00
co-authored by Claude Opus 5.5
parent efca73bcd4
commit 82d569da9c
18 changed files with 1348 additions and 11 deletions
+157
View File
@@ -0,0 +1,157 @@
package web
import (
"context"
"errors"
"net/http"
"strconv"
"time"
"supermarket/internal/api/hunter"
"supermarket/internal/enrich"
"supermarket/internal/prospects"
"supermarket/internal/secrets"
)
var hunterKey = secretField{"hunter", secrets.HunterAPIKey, "API key",
"In Hunter.io, API → API keys (hunter.io/api-keys).", "https://hunter.io/api-keys"}
// hunterBase is Hunter.io's API address; tests point it elsewhere.
var hunterBase = ""
// hunter is a client with the saved key, or nil without one.
func (s *Server) hunter() *hunter.Client {
key := s.Secrets.Get(secrets.HunterAPIKey)
if key == "" {
return nil
}
c := hunter.New(key)
if hunterBase != "" {
c.WithBase(hunterBase)
}
return c
}
var errNoHunter = errors.New("save a Hunter.io API key first, under Settings → Lead sources")
// enrichAction runs one Hunter.io call from the review screen.
func (s *Server) enrichAction(r *http.Request, kind, action string, id int64) error {
h := s.hunter()
if h == nil {
return errNoHunter
}
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Minute)
defer cancel()
now := time.Now()
var err error
switch kind + "/" + action {
case "company/people":
_, err = enrich.FindPeople(ctx, s.DB, h, id, enrich.LoadSettings(s.DB), now)
case "contact/find-email":
_, err = enrich.FindEmail(ctx, s.DB, h, id, now)
case "contact/verify":
_, err = enrich.Verify(ctx, s.DB, h, id, now)
}
return err
}
// maxVerify is how many addresses one click verifies, so the page answers
// within a few minutes.
const maxVerify = 50
// unverified lists the people on the review screen whose address hasn't
// been checked.
func unverified(companies []prospects.Company, loose []prospects.Contact) []int64 {
var ids []int64
add := func(p prospects.Contact) {
if p.Email != "" && p.EmailStatus == "" && p.Status == prospects.StatusNew {
ids = append(ids, p.ID)
}
}
for _, c := range companies {
for _, p := range c.Contacts {
add(p)
}
}
for _, p := range loose {
add(p)
}
return ids
}
// prospectsVerify verifies the unchecked addresses in New (for one signal,
// if the screen is filtered).
func (s *Server) prospectsVerify(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
filter, _ := strconv.ParseInt(r.PostFormValue("filter"), 10, 64)
tab := prospects.StatusNew
h := s.hunter()
if h == nil {
s.renderProspects(w, r, tab, filter, errNoHunter.Error())
return
}
companies, loose, err := prospects.Review(s.DB, tab, filter, 200)
if err != nil {
s.serverError(w, err)
return
}
ids := unverified(companies, loose)
if len(ids) > maxVerify {
ids = ids[:maxVerify]
}
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Minute)
defer cancel()
if n, err := enrich.VerifyMany(ctx, s.DB, h, ids, time.Now()); err != nil {
s.renderProspects(w, r, tab, filter, "Verified "+strconv.Itoa(n)+", then stopped: "+err.Error())
return
}
redirect(w, r, reviewURL(tab, filter), "verified")
}
// hunterSettingsData is the Hunter.io card on Settings → Lead sources.
func (s *Server) hunterSettingsData() map[string]any {
used, _ := enrich.CreditsSince(s.DB, time.Now().AddDate(0, 0, -30))
return map[string]any{
"Key": hunterKey,
"Set": s.Secrets.Has(secrets.HunterAPIKey),
"Settings": enrich.LoadSettings(s.DB),
"Departments": enrich.Departments,
"Seniorities": enrich.Seniorities,
"PerCompany": enrich.PerCompanyChoices,
"Used": strconv.FormatFloat(used, 'f', -1, 64),
}
}
// saveHunterSettings stores whom to look for, from the settings form.
func (s *Server) saveHunterSettings(r *http.Request) error {
per, _ := strconv.Atoi(r.PostFormValue("hunter_per_company"))
return enrich.SaveSettings(s.DB, enrich.Settings{
Departments: r.PostForm["hunter_department"],
Seniority: r.PostForm["hunter_seniority"],
PerCompany: per,
})
}
// testHunter checks the key and shows what's left of the plan.
func (s *Server) testHunter(ctx context.Context) map[string]any {
h := s.hunter()
if h == nil {
return map[string]any{"Error": "Save the key first."}
}
a, err := h.Account(ctx)
if err != nil {
return map[string]any{"Error": err.Error()}
}
msg := "The key works"
if a.PlanName != "" {
msg += " (" + a.PlanName + " plan)"
}
msg += ": " + a.Left()
if a.ResetDate != "" {
msg += " until " + a.ResetDate
}
return map[string]any{"OK": msg + "."}
}
+81
View File
@@ -0,0 +1,81 @@
package web
import (
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"supermarket/internal/enrich"
"supermarket/internal/prospects"
"supermarket/internal/secrets"
)
func TestHunterEnrichment(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/account":
w.Write([]byte(`{"data":{"plan_name":"Free","requests":{"credits":{"used":1,"available":50,"remaining":49}}}}`))
case "/domain-search":
w.Header().Set("X-Credits-Used", "1")
w.Write([]byte(`{"data":{"emails":[{"value":"pat@acme.example","type":"personal","confidence":94,"first_name":"Pat","last_name":"Lee","position":"CTO"}]}}`))
case "/email-verifier":
w.Header().Set("X-Credits-Used", "0.5")
w.Write([]byte(`{"data":{"status":"valid"}}`))
}
}))
defer srv.Close()
hunterBase = srv.URL
defer func() { hunterBase = "" }()
s, h := newTestServer(t, nil)
postForm(h, "/prospects/new", url.Values{"company_name": {"Acme"}, "website": {"acme.example"}})
// Without a key there's no button, and the action explains.
if body := do(h, http.MethodGet, "/prospects", nil, nil).Body.String(); strings.Contains(body, "Find people at") {
t.Error("Hunter button without a key")
}
if rec := postForm(h, "/prospects/company/1/people", url.Values{"tab": {"new"}}); !strings.Contains(rec.Body.String(), "save a Hunter.io API key first") {
t.Errorf("no key: %d", rec.Code)
}
// Settings: the key, whom to look for, and the test.
rec := postForm(h, "/settings/sources", url.Values{secrets.HunterAPIKey: {"k"},
"hunter_department": {"it", "finance"}, "hunter_seniority": {"executive"}, "hunter_per_company": {"10"}})
if rec.Code != http.StatusSeeOther {
t.Fatalf("save: %d %s", rec.Code, rec.Body)
}
if set := enrich.LoadSettings(s.DB); strings.Join(set.Departments, ",") != "it,finance" || set.PerCompany != 10 {
t.Errorf("settings: %+v", set)
}
if body := do(h, http.MethodGet, "/settings/sources", nil, nil).Body.String(); !strings.Contains(body, `value="finance" checked`) {
t.Error("the settings page doesn't show the saved departments")
}
if body := postForm(h, "/settings/sources/test/hunter", nil).Body.String(); !strings.Contains(body, "The key works (Free plan): 49 of 50 credits left") {
t.Errorf("test: %s", body)
}
// Find people, then verify the address.
if body := do(h, http.MethodGet, "/prospects", nil, nil).Body.String(); !strings.Contains(body, "Find people at acme.example") {
t.Error("no Hunter button with a key")
}
if rec := postForm(h, "/prospects/company/1/people", url.Values{"tab": {"new"}}); rec.Code != http.StatusSeeOther {
t.Fatalf("people: %d %s", rec.Code, rec.Body)
}
body := do(h, http.MethodGet, "/prospects", nil, nil).Body.String()
for _, want := range []string{"Pat Lee", "Found by Hunter.io", "1 person found, 1 new one.", "(1 credit)", "1 address hasn't been verified", "Verify the address"} {
if !strings.Contains(body, want) {
t.Errorf("review lacks %q", want)
}
}
if rec := postForm(h, "/prospects/verify", url.Values{}); rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/prospects?status=new&msg=verified" {
t.Fatalf("verify: %d %s", rec.Code, rec.Header().Get("Location"))
}
if p, _ := prospects.GetContact(s.DB, 1); p.EmailStatus != prospects.EmailValid {
t.Errorf("status: %+v", p)
}
if body := do(h, http.MethodGet, "/prospects", nil, nil).Body.String(); !strings.Contains(body, "verified</span>") || !strings.Contains(body, "receives mail") {
t.Error("the verification isn't shown")
}
}
+16
View File
@@ -8,7 +8,9 @@ import (
"time"
"supermarket/internal/crm"
"supermarket/internal/enrich"
"supermarket/internal/prospects"
"supermarket/internal/secrets"
"supermarket/internal/signals"
)
@@ -108,6 +110,11 @@ func (s *Server) renderProspects(w http.ResponseWriter, r *http.Request, tab str
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 {
@@ -130,6 +137,10 @@ func (s *Server) renderProspects(w http.ResponseWriter, r *http.Request, tab str
"Channels": signals.Channels,
"Back": reviewURL(tab, signalID),
"Today": time.Now().Format("2006-01-02"),
"Hunter": s.Secrets.Has(secrets.HunterAPIKey),
"Runs": runs,
"Unverified": len(unverified(companies, loose)),
"MaxVerify": maxVerify,
}})
}
@@ -165,6 +176,11 @@ func (s *Server) prospectAction(w http.ResponseWriter, r *http.Request) {
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":
+18 -5
View File
@@ -21,6 +21,7 @@ import (
"supermarket/internal/db"
"supermarket/internal/legacy"
"supermarket/internal/oauth"
"supermarket/internal/prospects"
"supermarket/internal/secrets"
"supermarket/internal/signals"
)
@@ -134,6 +135,7 @@ func (s *Server) Handler() (http.Handler, error) {
mux.HandleFunc("POST /prospects/new", s.prospectAdd)
mux.HandleFunc("GET /prospects/suppressed", s.suppressedPage)
mux.HandleFunc("POST /prospects/suppressed", s.suppressedAction)
mux.HandleFunc("POST /prospects/verify", s.prospectsVerify)
mux.HandleFunc("POST /prospects/{kind}/{id}/{action}", s.prospectAction)
mux.HandleFunc("GET /signals", s.signalsPage)
mux.HandleFunc("GET /signals/new", s.signalPage)
@@ -226,11 +228,20 @@ func sameOrigin(r *http.Request) bool {
func (s *Server) loadTemplates() error {
funcs := template.FuncMap{
"lines": func(v []string) string { return strings.Join(v, "\n") },
"join": strings.Join,
"ago": ago,
"add": func(a, b int) int { return a + b },
"hasPrefix": strings.HasPrefix,
"lines": func(v []string) string { return strings.Join(v, "\n") },
"join": strings.Join,
"ago": ago,
"add": func(a, b int) int { return a + b },
"hasPrefix": strings.HasPrefix,
"sourceLabel": prospects.SourceLabel,
"has": func(list []string, v string) bool {
for _, x := range list {
if x == v {
return true
}
}
return false
},
// dict builds a map from key, value pairs, to pass several values
// to a template.
"dict": func(kv ...any) (map[string]any, error) {
@@ -379,6 +390,8 @@ var flashes = map[string]string{
"discovering": "Searching. It takes a few minutes; new companies appear in Review, tagged with this signal.",
"rules-refreshed": "Rules refreshed.",
"imported": "Imported.",
"hunter-done": "Hunter.io search done: the result is on the card.",
"verified": "Checked with Hunter.io: the result is on each person.",
"oauth-expired": "That sign-in took too long or was already used. Try again.",
"dismissed": "Dismissed.",
"restored": "Restored.",
+8 -1
View File
@@ -341,6 +341,7 @@ func (s *Server) sourcesPage(w http.ResponseWriter, r *http.Request) {
s.render(w, r, "sources", page{Title: "Lead sources", Nav: "settings/sources", Data: map[string]any{
"Sources": s.leadSources(),
"Project": s.origamiProject(),
"Hunter": s.hunterSettingsData(),
}})
}
@@ -349,7 +350,7 @@ func (s *Server) sourcesSave(w http.ResponseWriter, r *http.Request) {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err := s.saveSecrets(r, leadSourceKeys); err != nil {
if err := s.saveSecrets(r, append(leadSourceKeys, hunterKey)); err != nil {
s.serverError(w, err)
return
}
@@ -357,6 +358,10 @@ func (s *Server) sourcesSave(w http.ResponseWriter, r *http.Request) {
s.serverError(w, err)
return
}
if err := s.saveHunterSettings(r); err != nil {
s.serverError(w, err)
return
}
redirect(w, r, "/settings/sources", "saved")
}
@@ -382,6 +387,8 @@ func (s *Server) sourcesTest(w http.ResponseWriter, r *http.Request) {
if who != "" {
data["OK"] = "The key works (" + who + ")."
}
case "hunter":
data = s.testHunter(ctx)
case signals.SourceOrigami:
key := s.Secrets.Get(secrets.OrigamiAPIKey)
if key == "" {
+5
View File
@@ -421,3 +421,8 @@ pre.sample { max-height: 24rem; overflow: auto; font-size: 0.78rem; }
#discovery .grid { margin-top: 0.5rem; }
#discovery h3 { margin: 0 0 0.3rem; }
table.runs { margin-top: 0.75rem; }
/* Enrichment */
.check-grid { display: flex; flex-wrap: wrap; gap: 0.25rem 1rem; margin-bottom: 0.5rem; }
.inline-note { display: flex; flex-wrap: wrap; align-items: center; gap: 0.5rem; margin: 0.35rem 0; }
.error-text { color: hsl(var(--destructive)); }
+26 -2
View File
@@ -25,6 +25,13 @@
</nav>
{{if and (eq $tab "new") (or .Companies .Loose)}}
{{if and .Hunter .Unverified}}
<form method="post" action="/prospects/verify" class="inline-note" data-busy="Verifying…">
<input type="hidden" name="filter" value="{{.Signal}}">
<span class="small">{{.Unverified}} {{if eq .Unverified 1}}address hasn't{{else}}addresses haven't{{end}} been verified{{if gt .Unverified .MaxVerify}} ({{.MaxVerify}} are checked at a time){{end}}.</span>
<button type="submit" class="secondary small">Verify with Hunter.io</button>
</form>
{{end}}
<p class="help">{{if .Synced.IsZero}}Your CRM hasn't been synced yet, so Supermarket can't warn you about records you already have.{{else}}Checked against your CRM as of {{ago .Synced}}.{{end}}</p>
{{end}}
@@ -56,6 +63,13 @@
</div>
{{with .Why}}<p class="why">{{.}}</p>{{end}}
<p class="meta">{{template "provenance" .}}</p>
{{if and $d.Hunter .Domain (ne .Status "rejected")}}
<form method="post" action="/prospects/company/{{.ID}}/people" class="inline-note" data-busy="Searching Hunter.io…">
<input type="hidden" name="tab" value="{{$tab}}"><input type="hidden" name="filter" value="{{$d.Signal}}">
<button type="submit" class="secondary small">Find people at {{.Domain}}</button>
{{template "enrich-run" (index $d.Runs (printf "company:%d" .ID))}}
</form>
{{else}}{{template "enrich-run" (index $d.Runs (printf "company:%d" .ID))}}{{end}}
{{template "signal-tag" dict "Kind" "company" "ID" .ID "SignalID" .SignalID "D" $d}}
{{with index $matches (printf "company:%d" .ID)}}{{template "crm-matches" .}}{{end}}
@@ -92,11 +106,19 @@
<div>
<strong>{{$p.Name}}</strong>{{with $p.Title}} · {{.}}{{end}}{{if ne $p.Status $tab}} <span class="badge">{{template "prospect-status" $p.Status}}</span>{{end}}
<div class="meta">
{{with $p.Email}}<a href="mailto:{{.}}">{{.}}</a>{{if eq $p.EmailStatus "valid"}} <span class="badge published">verified</span>{{else if eq $p.EmailStatus "risky"}} <span class="badge">risky</span>{{else if eq $p.EmailStatus "invalid"}} <span class="badge failed">bounces</span>{{else}} <span class="muted">not verified</span>{{end}}{{end}}
{{with $p.Email}}<a href="mailto:{{.}}">{{.}}</a>{{if eq $p.EmailStatus "valid"}} <span class="badge published">verified</span>{{else if eq $p.EmailStatus "risky"}} <span class="badge">risky</span>{{else if eq $p.EmailStatus "invalid"}} <span class="badge failed">bounces</span>{{else if eq $p.EmailStatus "unknown"}} <span class="muted">couldn't be verified</span>{{else}} <span class="muted">not verified</span>{{end}}{{end}}
{{with $p.Phone}} · {{.}}{{end}}
{{with $p.LinkedIn}} · <a href="{{.}}" target="_blank" rel="noopener noreferrer">LinkedIn</a>{{end}}
</div>
<div class="meta">{{template "provenance" $p}}</div>
{{if and $d.Hunter (ne $p.Status "rejected")}}
{{if and (not $p.Email) $p.CompanyID}}
<form method="post" action="/prospects/contact/{{$p.ID}}/find-email" class="inline-note" data-busy="Searching Hunter.io…"><input type="hidden" name="tab" value="{{$tab}}"><input type="hidden" name="filter" value="{{$d.Signal}}"><button type="submit" class="link small">Find their email</button></form>
{{else if and $p.Email (not $p.EmailStatus)}}
<form method="post" action="/prospects/contact/{{$p.ID}}/verify" class="inline-note" data-busy="Verifying…"><input type="hidden" name="tab" value="{{$tab}}"><input type="hidden" name="filter" value="{{$d.Signal}}"><button type="submit" class="link small">Verify the address</button></form>
{{end}}
{{end}}
{{template "enrich-run" (index $d.Runs (printf "contact:%d" $p.ID))}}
{{if not $p.CompanyID}}{{template "signal-tag" dict "Kind" "contact" "ID" $p.ID "SignalID" $p.SignalID "D" $d}}{{end}}
{{with index .Matches (printf "contact:%d" $p.ID)}}{{template "crm-matches" .}}{{end}}
{{template "outcomes" dict "Kind" "contact" "ID" $p.ID "Tab" $tab "D" $d}}
@@ -120,7 +142,9 @@
{{define "prospect-status"}}{{if eq . "new"}}new{{else if eq . "accepted"}}accepted{{else}}set aside{{end}}{{end}}
{{define "provenance"}}{{if eq .Source "manual"}}Added by hand{{else}}Found by {{.Source}}{{end}} {{ago .FoundAt}}{{with .SourceDetail}} · {{if or (hasPrefix . "https://") (hasPrefix . "http://")}}<a href="{{.}}" target="_blank" rel="noopener noreferrer">source</a>{{else}}{{.}}{{end}}{{end}}{{end}}
{{define "enrich-run"}}{{if .ID}}<span class="small {{if .Error}}error-text{{else}}muted{{end}}">Hunter.io {{ago .At}}: {{if .Error}}{{.Error}}{{else}}{{.Result}}{{end}}{{if .Credits}} ({{.Credits}} {{if eq .Credits 1.0}}credit{{else}}credits{{end}}){{end}}</span>{{end}}{{end}}
{{define "provenance"}}{{if eq .Source "manual"}}Added by hand{{else}}Found by {{sourceLabel .Source}}{{end}} {{ago .FoundAt}}{{with .SourceDetail}} · {{if or (hasPrefix . "https://") (hasPrefix . "http://")}}<a href="{{.}}" target="_blank" rel="noopener noreferrer">source</a>{{else}}{{.}}{{end}}{{end}}{{end}}
{{define "crm-matches"}}
<p class="warnings">Already in your CRM: {{range $i, $r := .}}{{if $i}}, {{end}}{{$r.Entity}} <strong>{{$r.Name}}</strong>{{with $r.Email}} ({{.}}){{end}}{{end}}.</p>
+24
View File
@@ -18,6 +18,30 @@
{{end}}
</section>
{{end}}
{{with .Hunter}}
<h2 id="hunter">Enrichment</h2>
<section class="card">
<h3>Hunter.io</h3>
<p class="small">Finds the people in the roles you sell to at a prospect's website domain, the work address of a person whose name you know, and whether an address receives mail. You start each search from <a href="/prospects">Review</a>; nothing runs on its own. A search costs a credit when it finds someone, a verification half a credit.{{if ne .Used "0"}} Used in the last 30 days: <strong>{{.Used}}</strong> credits.{{end}}</p>
{{template "key-field" (dict "F" .Key "Set" .Set)}}
<fieldset>
<legend>Whom to look for at a company</legend>
<p class="help">Departments (none ticked: all of them)</p>
<div class="check-grid">{{$set := .Settings}}{{range .Departments}}<label class="check"><input type="checkbox" name="hunter_department" value="{{.ID}}" {{if has $set.Departments .ID}}checked{{end}}> {{.Label}}</label>{{end}}</div>
<p class="help">Seniority (none ticked: any)</p>
<div class="check-grid">{{range .Seniorities}}<label class="check"><input type="checkbox" name="hunter_seniority" value="{{.ID}}" {{if has $set.Seniority .ID}}checked{{end}}> {{.Label}}</label>{{end}}</div>
<label>At most
<select name="hunter_per_company">{{range .PerCompany}}<option value="{{.}}" {{if eq . $set.PerCompany}}selected{{end}}>{{.}} people a company</option>{{end}}</select>
<span class="help">Hunter.io's free plan returns at most 10 a search.</span>
</label>
</fieldset>
{{if .Set}}
<button type="button" class="secondary small" hx-post="/settings/sources/test/hunter" hx-target="#test-hunter" hx-indicator="#testing-hunter">Test</button>
<span id="testing-hunter" class="htmx-indicator">Checking…</span>
<div id="test-hunter"></div>
{{end}}
</section>
{{end}}
<div class="actions"><button type="submit">Save</button></div>
</form>
{{end}}{{template "settings-end"}}{{end}}