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
+277
View File
@@ -0,0 +1,277 @@
// Package hunter finds and verifies work email addresses through Hunter.io's
// API (https://hunter.io/api-documentation/v2). Searches and verifications
// use the account's credits; the account call is free.
package hunter
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
const apiBase = "https://api.hunter.io/v2"
var (
// ErrUnauthorized means the key was refused.
ErrUnauthorized = errors.New("Hunter.io refused the API key")
// ErrNoCredits means the plan's searches or verifications are used up.
ErrNoCredits = errors.New("Hunter.io says this month's credits are used up (HTTP 429)")
// ErrRateLimited means too many calls too quickly.
ErrRateLimited = errors.New("Hunter.io's rate limit was reached; try again in a minute")
)
// Client calls the API with one key.
type Client struct {
key, base string
http *http.Client
// Pause between polls of a verification that's still running.
poll time.Duration
}
func New(key string) *Client {
return &Client{key: key, base: apiBase, http: &http.Client{Timeout: 40 * time.Second}, poll: 5 * time.Second}
}
// WithBase points the client at another server (for tests), and polls
// without waiting.
func (c *Client) WithBase(u string) *Client {
c.base = strings.TrimRight(u, "/")
c.poll = time.Millisecond
return c
}
// get calls path and decodes the response's "data" into out. It returns
// the credits the call used (the X-Credits-Used header) and the status.
func (c *Client) get(ctx context.Context, path string, q url.Values, out any) (credits float64, status int, err error) {
u := c.base + path
if len(q) > 0 {
u += "?" + q.Encode()
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
if err != nil {
return 0, 0, err
}
req.Header.Set("X-API-KEY", c.key)
req.Header.Set("Accept", "application/json")
res, err := c.http.Do(req)
if err != nil {
return 0, 0, err
}
defer res.Body.Close()
raw, err := io.ReadAll(io.LimitReader(res.Body, 8<<20))
if err != nil {
return 0, res.StatusCode, err
}
credits, _ = strconv.ParseFloat(res.Header.Get("X-Credits-Used"), 64)
switch res.StatusCode {
case http.StatusOK, http.StatusAccepted:
case http.StatusUnauthorized:
return 0, res.StatusCode, ErrUnauthorized
case http.StatusTooManyRequests:
return 0, res.StatusCode, ErrNoCredits
case http.StatusForbidden:
return 0, res.StatusCode, ErrRateLimited
default:
return credits, res.StatusCode, fmt.Errorf("Hunter.io %s: HTTP %d: %s", path, res.StatusCode, errorDetail(raw))
}
if res.StatusCode == http.StatusAccepted {
return credits, res.StatusCode, nil
}
var env struct {
Data json.RawMessage `json:"data"`
}
if err := json.Unmarshal(raw, &env); err != nil {
return credits, res.StatusCode, fmt.Errorf("Hunter.io %s: %w", path, err)
}
if len(env.Data) == 0 || string(env.Data) == "null" {
return credits, res.StatusCode, nil
}
return credits, res.StatusCode, json.Unmarshal(env.Data, out)
}
// errorDetail is the first error's details, or the start of the body.
func errorDetail(raw []byte) string {
var e struct {
Errors []struct {
ID string `json:"id"`
Details string `json:"details"`
} `json:"errors"`
}
if json.Unmarshal(raw, &e) == nil && len(e.Errors) > 0 {
if e.Errors[0].Details != "" {
return e.Errors[0].Details
}
return e.Errors[0].ID
}
return strings.TrimSpace(string(raw[:min(len(raw), 300)]))
}
// Quota is what's left of one kind of request this period.
type Quota struct {
Used float64 `json:"used"`
Available float64 `json:"available"`
Remaining float64 `json:"remaining"`
}
// Account is the key owner's plan and what's left of it.
type Account struct {
Email string `json:"email"`
PlanName string `json:"plan_name"`
ResetDate string `json:"reset_date"`
Requests struct {
Credits *Quota `json:"credits"` // only on single-pool plans
Searches Quota `json:"searches"`
Verifications Quota `json:"verifications"`
} `json:"requests"`
}
// Left describes what's left, for the settings page.
func (a *Account) Left() string {
if q := a.Requests.Credits; q != nil {
return fmt.Sprintf("%s of %s credits left", num(q.Remaining), num(q.Available))
}
return fmt.Sprintf("%s of %s searches and %s of %s verifications left",
num(a.Requests.Searches.Remaining), num(a.Requests.Searches.Available),
num(a.Requests.Verifications.Remaining), num(a.Requests.Verifications.Available))
}
func num(f float64) string { return strconv.FormatFloat(f, 'f', -1, 64) }
// Account checks the key. It costs nothing.
func (c *Client) Account(ctx context.Context) (*Account, error) {
var a Account
if _, _, err := c.get(ctx, "/account", nil, &a); err != nil {
return nil, err
}
return &a, nil
}
// Verification is Hunter's last check of an address.
type Verification struct {
Date string `json:"date"`
Status string `json:"status"` // valid, accept_all, unknown (invalid ones aren't returned)
}
// Email is a person Domain Search found.
type Email struct {
Value string `json:"value"`
Type string `json:"type"` // personal or generic
Confidence int `json:"confidence"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Position string `json:"position"`
Seniority string `json:"seniority"`
Department string `json:"department"`
DecisionMaker bool `json:"decision_maker"`
LinkedIn string `json:"linkedin"`
PhoneNumber string `json:"phone_number"`
Verification Verification `json:"verification"`
}
// DomainQuery says whom to look for at a domain.
type DomainQuery struct {
Domain string
Limit int // 1 to 100; on the free plan at most 10
Seniority []string // junior, senior, executive
Departments []string // executive, it, finance, management, sales, …
}
// DomainResult is what Domain Search found.
type DomainResult struct {
Organization string `json:"organization"`
Pattern string `json:"pattern"`
AcceptAll bool `json:"accept_all"`
Emails []Email `json:"emails"`
Credits float64 `json:"-"`
}
// DomainSearch finds people with personal addresses at a domain. It costs a
// search when anything is found.
func (c *Client) DomainSearch(ctx context.Context, q DomainQuery) (*DomainResult, error) {
v := url.Values{"domain": {q.Domain}, "type": {"personal"}}
if q.Limit > 0 {
v.Set("limit", strconv.Itoa(q.Limit))
}
if len(q.Seniority) > 0 {
v.Set("seniority", strings.Join(q.Seniority, ","))
}
if len(q.Departments) > 0 {
v.Set("department", strings.Join(q.Departments, ","))
}
var out DomainResult
credits, _, err := c.get(ctx, "/domain-search", v, &out)
out.Credits = credits
if err != nil {
return nil, err
}
return &out, nil
}
// Found is the address Email Finder found for a person.
type Found struct {
Email string `json:"email"`
Score int `json:"score"`
Position string `json:"position"`
LinkedInURL string `json:"linkedin_url"`
PhoneNumber string `json:"phone_number"`
Verification Verification `json:"verification"`
Credits float64 `json:"-"`
}
// FindEmail looks for a person's address at a domain. It costs a search
// only when an address is found; Email is "" otherwise.
func (c *Client) FindEmail(ctx context.Context, domain, first, last string) (*Found, error) {
v := url.Values{"domain": {domain}}
if first != "" && last != "" {
v.Set("first_name", first)
v.Set("last_name", last)
} else {
v.Set("full_name", strings.TrimSpace(first+" "+last))
}
var out Found
credits, _, err := c.get(ctx, "/email-finder", v, &out)
out.Credits = credits
if err != nil {
return nil, err
}
return &out, nil
}
// Checked is the result of verifying an address.
type Checked struct {
Status string `json:"status"` // valid, invalid, accept_all, webmail, disposable, unknown
Score int `json:"score"`
Credits float64 `json:"-"`
}
// Verify checks whether an address receives mail. Hunter answers 202 while
// a check runs (up to about 20 seconds); Verify asks again until it's done,
// which is counted once.
func (c *Client) Verify(ctx context.Context, email string) (*Checked, error) {
var out Checked
for attempt := 0; ; attempt++ {
credits, status, err := c.get(ctx, "/email-verifier", url.Values{"email": {email}}, &out)
out.Credits += credits
if err != nil {
return nil, err
}
if status != http.StatusAccepted {
return &out, nil
}
if attempt >= 6 {
return nil, errors.New("Hunter.io is still checking " + email + "; try again later")
}
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(c.poll):
}
}
}
+82
View File
@@ -0,0 +1,82 @@
package hunter
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"testing"
)
func TestClient(t *testing.T) {
verifyCalls := 0
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("X-API-KEY") != "k" {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte(`{"errors":[{"id":"authentication_failed","code":401,"details":"No user found"}]}`))
return
}
q := r.URL.Query()
switch r.URL.Path {
case "/account":
w.Write([]byte(`{"data":{"email":"pat@example.com","plan_name":"Free","reset_date":"2026-12-01",
"requests":{"searches":{"used":3,"available":25,"remaining":22},"verifications":{"used":1,"available":50,"remaining":49}}}}`))
case "/domain-search":
if q.Get("domain") != "acme.example" || q.Get("type") != "personal" || q.Get("limit") != "5" ||
q.Get("seniority") != "executive,senior" || q.Get("department") != "it" {
t.Errorf("domain search query: %v", q)
}
w.Header().Set("X-Credits-Used", "1")
w.Write([]byte(`{"data":{"organization":"Acme","pattern":"{first}","emails":[{"value":"pat@acme.example","type":"personal",
"confidence":94,"first_name":"Pat","last_name":"Lee","position":"CTO","department":"it",
"verification":{"date":"2026-11-01","status":"valid"}}]},"meta":{"results":1}}`))
case "/email-finder":
if q.Get("first_name") != "Ann" || q.Get("last_name") != "Ray" {
t.Errorf("finder query: %v", q)
}
w.Write([]byte(`{"data":{"email":null,"score":null}}`))
case "/email-verifier":
verifyCalls++
if verifyCalls == 1 {
w.WriteHeader(http.StatusAccepted)
return
}
w.Header().Set("X-Credits-Used", "0.5")
w.Write([]byte(`{"data":{"status":"accept_all","score":70,"email":"pat@acme.example"}}`))
case "/quota":
w.WriteHeader(http.StatusTooManyRequests)
default:
w.WriteHeader(http.StatusNotFound)
w.Write([]byte(`{"errors":[{"id":"not_found","code":404,"details":"Nothing here"}]}`))
}
}))
defer srv.Close()
ctx := context.Background()
c := New("k").WithBase(srv.URL)
a, err := c.Account(ctx)
if err != nil || a.PlanName != "Free" || a.Left() != "22 of 25 searches and 49 of 50 verifications left" {
t.Fatalf("account: %+v %v", a, err)
}
res, err := c.DomainSearch(ctx, DomainQuery{Domain: "acme.example", Limit: 5, Seniority: []string{"executive", "senior"}, Departments: []string{"it"}})
if err != nil || len(res.Emails) != 1 || res.Credits != 1 || res.Emails[0].Verification.Status != "valid" || res.Emails[0].Position != "CTO" {
t.Fatalf("domain search: %+v %v", res, err)
}
f, err := c.FindEmail(ctx, "acme.example", "Ann", "Ray")
if err != nil || f.Email != "" {
t.Fatalf("finder: %+v %v", f, err)
}
v, err := c.Verify(ctx, "pat@acme.example")
if err != nil || v.Status != "accept_all" || v.Credits != 0.5 || verifyCalls != 2 {
t.Fatalf("verify: %+v %v (%d calls)", v, err, verifyCalls)
}
if _, _, err := c.get(ctx, "/quota", nil, &struct{}{}); !errors.Is(err, ErrNoCredits) {
t.Errorf("quota: %v", err)
}
if _, _, err := c.get(ctx, "/nope", nil, &struct{}{}); err == nil || err.Error() != "Hunter.io /nope: HTTP 404: Nothing here" {
t.Errorf("404: %v", err)
}
if _, err := New("bad").WithBase(srv.URL).Account(ctx); !errors.Is(err, ErrUnauthorized) {
t.Errorf("bad key: %v", err)
}
}
+17
View File
@@ -298,6 +298,23 @@ CREATE TABLE discovery_runs (
notes TEXT NOT NULL DEFAULT '[]' -- JSON: why companies were skipped
);
CREATE INDEX discovery_runs_by_signal ON discovery_runs (signal_id, id);
`,
// 9: enrichment with Hunter.io. Every search and verification is kept,
// with what it found and the credits it used.
`
CREATE TABLE enrich_runs (
id INTEGER PRIMARY KEY,
kind TEXT NOT NULL, -- people (at a company), email (for a person), verify
subject TEXT NOT NULL, -- company:3, contact:12
at TEXT NOT NULL,
found INTEGER NOT NULL DEFAULT 0,
added INTEGER NOT NULL DEFAULT 0,
credits REAL NOT NULL DEFAULT 0, -- Hunter.io credits used
result TEXT NOT NULL DEFAULT '', -- what happened, in words
error TEXT NOT NULL DEFAULT ''
);
CREATE INDEX enrich_runs_by_subject ON enrich_runs (subject, id);
CREATE INDEX enrich_runs_by_time ON enrich_runs (at);
`,
}
+384
View File
@@ -0,0 +1,384 @@
// Package enrich fills in the people at prospective companies, and their
// work email addresses, through Hunter.io: the people in the roles you sell
// to at a company's domain, an address for a person whose name you know,
// and whether an address receives mail. Everything found goes to Review
// like any other prospect, and every call is kept with the credits it used.
package enrich
import (
"context"
"database/sql"
"errors"
"fmt"
"strings"
"time"
"supermarket/internal/api/hunter"
"supermarket/internal/db"
"supermarket/internal/prospects"
)
// Kinds of run.
const (
KindPeople = "people" // Domain Search at a company
KindEmail = "email" // Email Finder for a person
KindVerify = "verify" // Email Verifier
)
// Settings say whom to look for at a company.
type Settings struct {
Departments []string `json:"departments"`
Seniority []string `json:"seniority"`
PerCompany int `json:"per_company"`
}
// Option is a value Hunter.io accepts, with its label.
type Option struct{ ID, Label string }
// Departments Hunter.io knows.
var Departments = []Option{
{"executive", "Executive"}, {"management", "Management"}, {"it", "IT"}, {"operations", "Operations"},
{"finance", "Finance"}, {"sales", "Sales"}, {"marketing", "Marketing"}, {"legal", "Legal"},
{"hr", "HR"}, {"support", "Support"}, {"administrative", "Administrative"}, {"education", "Education"},
{"health", "Health"}, {"design", "Design"}, {"communication", "Communication"}, {"product", "Product"},
{"research", "Research"}, {"consulting", "Consulting"}, {"procurement", "Procurement"},
}
// Seniorities Hunter.io knows.
var Seniorities = []Option{{"executive", "Executive"}, {"senior", "Senior"}, {"junior", "Junior"}}
// PerCompanyChoices are the sizes offered. Hunter.io's free plan returns at
// most 10 people a search.
var PerCompanyChoices = []int{3, 5, 10}
// DefaultSettings look for senior people in the departments that buy
// business software.
var DefaultSettings = Settings{
Departments: []string{"executive", "management", "it", "operations"},
Seniority: []string{"executive", "senior"},
PerCompany: 5,
}
const settingsKey = "enrich:hunter"
// LoadSettings returns the saved settings, or the defaults.
func LoadSettings(d *db.DB) Settings {
s := DefaultSettings
if ok, err := d.GetJSON(settingsKey, &s); err != nil || !ok {
return DefaultSettings
}
return s.clean()
}
// SaveSettings stores the settings, keeping only values Hunter.io knows.
func SaveSettings(d *db.DB, s Settings) error {
return d.PutJSON(settingsKey, s.clean())
}
func (s Settings) clean() Settings {
s.Departments = known(s.Departments, Departments)
s.Seniority = known(s.Seniority, Seniorities)
if s.PerCompany < 1 {
s.PerCompany = DefaultSettings.PerCompany
}
s.PerCompany = min(s.PerCompany, 100)
return s
}
func known(vals []string, opts []Option) []string {
out := []string{}
for _, o := range opts {
for _, v := range vals {
if v == o.ID {
out = append(out, v)
break
}
}
}
return out
}
// Run is one call to Hunter.io and what came of it.
type Run struct {
ID int64
Kind string
Subject string
At time.Time
Found int
Added int
Credits float64
Result string
Error string
}
const timeFormat = time.RFC3339
func record(d *db.DB, r *Run) error {
res, err := d.Exec(`INSERT INTO enrich_runs (kind, subject, at, found, added, credits, result, error)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, r.Kind, r.Subject, r.At.UTC().Format(timeFormat),
r.Found, r.Added, r.Credits, r.Result, r.Error)
if err != nil {
return err
}
r.ID, err = res.LastInsertId()
return err
}
// finish records a run, with its error if it failed.
func finish(d *db.DB, r *Run, err error) (*Run, error) {
if err != nil {
r.Error = err.Error()
}
if rerr := record(d, r); rerr != nil && err == nil {
err = rerr
}
return r, err
}
// Latest is each subject's most recent run.
func Latest(d *db.DB, subjects ...string) (map[string]Run, error) {
out := map[string]Run{}
if len(subjects) == 0 {
return out, nil
}
marks := strings.TrimSuffix(strings.Repeat("?,", len(subjects)), ",")
args := make([]any, len(subjects))
for i, s := range subjects {
args[i] = s
}
rows, err := d.Query(`SELECT id, kind, subject, at, found, added, credits, result, error FROM enrich_runs
WHERE id IN (SELECT max(id) FROM enrich_runs WHERE subject IN (`+marks+`) GROUP BY subject)`, args...)
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var r Run
var at string
if err := rows.Scan(&r.ID, &r.Kind, &r.Subject, &at, &r.Found, &r.Added, &r.Credits, &r.Result, &r.Error); err != nil {
return nil, err
}
r.At, _ = time.Parse(timeFormat, at)
out[r.Subject] = r
}
return out, rows.Err()
}
// CreditsSince is how many credits were used since a time.
func CreditsSince(d *db.DB, since time.Time) (float64, error) {
var n sql.NullFloat64
err := d.QueryRow(`SELECT sum(credits) FROM enrich_runs WHERE at >= ?`, since.UTC().Format(timeFormat)).Scan(&n)
return n.Float64, err
}
// fromSearch is the status for an address Domain Search or Email Finder
// returned, from Hunter.io's last check of it.
func fromSearch(v hunter.Verification) string {
switch v.Status {
case "valid":
return prospects.EmailValid
case "accept_all":
return prospects.EmailRisky
case "invalid":
return prospects.EmailInvalid
}
return ""
}
// fromVerifier is the status for an Email Verifier result.
func fromVerifier(status string) string {
switch status {
case "valid":
return prospects.EmailValid
case "invalid", "disposable":
return prospects.EmailInvalid
case "accept_all", "webmail":
return prospects.EmailRisky
}
return prospects.EmailUnknown
}
func plural(n int, one, many string) string {
if n == 1 {
return "1 " + one
}
return fmt.Sprintf("%d %s", n, many)
}
// FindPeople looks for people in the roles the settings name at a
// company's domain, and adds them to Review under it.
func FindPeople(ctx context.Context, d *db.DB, h *hunter.Client, companyID int64, set Settings, now time.Time) (*Run, error) {
c, err := prospects.GetCompany(d, companyID)
if err != nil {
return nil, err
}
if c.Domain == "" {
return nil, errors.New(c.Name + " has no website, so there's no domain to search")
}
if sup, err := prospects.IsSuppressed(d, "", c.Domain); err != nil || sup {
if err == nil {
err = fmt.Errorf("%s: %w", c.Domain, prospects.ErrSuppressed)
}
return nil, err
}
run := &Run{Kind: KindPeople, Subject: prospects.Subject("company", c.ID), At: now}
res, err := h.DomainSearch(ctx, hunter.DomainQuery{
Domain: c.Domain, Limit: set.PerCompany, Seniority: set.Seniority, Departments: set.Departments,
})
if res != nil {
run.Credits = res.Credits
}
if err != nil {
return finish(d, run, err)
}
var existing, skipped int
for _, e := range res.Emails {
if e.Type == "generic" || e.Value == "" {
continue
}
run.Found++
detail := fmt.Sprintf("Hunter.io, %d%% confidence", e.Confidence)
if e.Department != "" {
detail += ", " + e.Department
}
_, added, err := prospects.AddContact(d, prospects.Contact{
CompanyID: c.ID, FirstName: e.FirstName, LastName: e.LastName, Title: e.Position,
Email: e.Value, EmailStatus: fromSearch(e.Verification), LinkedIn: e.LinkedIn, Phone: e.PhoneNumber,
Source: prospects.SourceHunter, SourceDetail: detail,
}, now)
switch {
case errors.Is(err, prospects.ErrSuppressed):
skipped++
case err != nil:
return finish(d, run, err)
case added:
run.Added++
default:
existing++
}
}
switch {
case run.Found == 0:
run.Result = "Nobody in those roles found at " + c.Domain + "."
default:
run.Result = plural(run.Found, "person", "people") + " found, " + plural(run.Added, "new one", "new ones")
if existing > 0 {
run.Result += ", " + plural(existing, "already a prospect", "already prospects")
}
if skipped > 0 {
run.Result += ", " + plural(skipped, "on the suppression list", "on the suppression list")
}
run.Result += "."
}
return finish(d, run, nil)
}
// FindEmail looks for the work address of a person whose name and company
// are known; origami.chat, for one, often has no address.
func FindEmail(ctx context.Context, d *db.DB, h *hunter.Client, contactID int64, now time.Time) (*Run, error) {
p, err := prospects.GetContact(d, contactID)
if err != nil {
return nil, err
}
if p.Email != "" {
return nil, errors.New(p.Name() + " already has an address")
}
if p.FirstName == "" && p.LastName == "" {
return nil, errors.New("give the person's name first")
}
if p.CompanyID == 0 {
return nil, errors.New(p.Name() + " has no company, so there's no domain to search")
}
c, err := prospects.GetCompany(d, p.CompanyID)
if err != nil {
return nil, err
}
if c.Domain == "" {
return nil, errors.New(c.Name + " has no website, so there's no domain to search")
}
run := &Run{Kind: KindEmail, Subject: prospects.Subject("contact", p.ID), At: now}
f, err := h.FindEmail(ctx, c.Domain, p.FirstName, p.LastName)
if f != nil {
run.Credits = f.Credits
}
if err != nil {
return finish(d, run, err)
}
if f.Email == "" {
run.Result = "No address found at " + c.Domain + "."
return finish(d, run, nil)
}
run.Found = 1
if err := prospects.SetEmail(d, p.ID, f.Email, fromSearch(f.Verification)); err != nil {
run.Result = "Found " + f.Email + ", but it wasn't saved."
return finish(d, run, err)
}
run.Added = 1
run.Result = fmt.Sprintf("Found %s (%d%% confidence).", f.Email, f.Score)
return finish(d, run, nil)
}
// Verify checks whether a person's address receives mail.
func Verify(ctx context.Context, d *db.DB, h *hunter.Client, contactID int64, now time.Time) (*Run, error) {
p, err := prospects.GetContact(d, contactID)
if err != nil {
return nil, err
}
if p.Email == "" {
return nil, errors.New(p.Name() + " has no address to verify")
}
run := &Run{Kind: KindVerify, Subject: prospects.Subject("contact", p.ID), At: now}
c, err := h.Verify(ctx, p.Email)
if c != nil {
run.Credits = c.Credits
}
if err != nil {
return finish(d, run, err)
}
status := fromVerifier(c.Status)
if err := prospects.SetEmailStatus(d, p.ID, status); err != nil {
return finish(d, run, err)
}
run.Found = 1
run.Result = verdict(p.Email, c.Status)
return finish(d, run, nil)
}
func verdict(email, status string) string {
switch status {
case "valid":
return email + " receives mail."
case "invalid":
return email + " bounces."
case "disposable":
return email + " is a throwaway address."
case "accept_all":
return "The server accepts any address, so " + email + " can't be confirmed."
case "webmail":
return email + " is a personal webmail address, not a work one."
}
return "Hunter.io couldn't tell whether " + email + " receives mail."
}
// Stop reports whether an error means further calls would fail too: the
// key is refused, the credits are gone, or the rate limit was reached.
func Stop(err error) bool {
return errors.Is(err, hunter.ErrUnauthorized) || errors.Is(err, hunter.ErrNoCredits) ||
errors.Is(err, hunter.ErrRateLimited) || errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled)
}
// VerifyMany verifies several people's addresses, stopping when Hunter.io
// can't take more. It returns how many were checked.
func VerifyMany(ctx context.Context, d *db.DB, h *hunter.Client, ids []int64, now time.Time) (int, error) {
n := 0
for _, id := range ids {
_, err := Verify(ctx, d, h, id, now)
if err != nil && Stop(err) {
return n, err
}
if err == nil {
n++
}
}
return n, nil
}
+170
View File
@@ -0,0 +1,170 @@
package enrich
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"testing"
"time"
"supermarket/internal/api/hunter"
"supermarket/internal/db"
"supermarket/internal/prospects"
)
var now = time.Date(2026, 11, 22, 10, 0, 0, 0, time.UTC)
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
}
// fake answers like Hunter.io.
func fake(t *testing.T) *hunter.Client {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
switch r.URL.Path {
case "/domain-search":
w.Header().Set("X-Credits-Used", "1")
if q.Get("domain") == "empty.example" {
w.Write([]byte(`{"data":{"emails":[]}}`))
return
}
w.Write([]byte(`{"data":{"emails":[
{"value":"pat@acme.example","type":"personal","confidence":94,"first_name":"Pat","last_name":"Lee","position":"CTO","department":"it","verification":{"status":"valid"}},
{"value":"info@acme.example","type":"generic"},
{"value":"kim@acme.example","type":"personal","confidence":60,"first_name":"Kim","last_name":"Ng","verification":{"status":"accept_all"}},
{"value":"no@acme.example","type":"personal","first_name":"No","last_name":"Body"}]}}`))
case "/email-finder":
if q.Get("last_name") == "Unknown" {
w.Write([]byte(`{"data":{"email":null}}`))
return
}
w.Header().Set("X-Credits-Used", "1")
w.Write([]byte(`{"data":{"email":"ann.ray@acme.example","score":91,"verification":{"status":"valid"}}}`))
case "/email-verifier":
w.Header().Set("X-Credits-Used", "0.5")
status := map[string]string{"pat@acme.example": "invalid", "kim@acme.example": "webmail"}[q.Get("email")]
if q.Get("email") == "quota@acme.example" {
w.WriteHeader(http.StatusTooManyRequests)
return
}
if status == "" {
status = "unknown"
}
w.Write([]byte(`{"data":{"status":"` + status + `"}}`))
}
}))
t.Cleanup(srv.Close)
return hunter.New("k").WithBase(srv.URL)
}
func TestFindPeople(t *testing.T) {
d := openDB(t)
h := fake(t)
ctx := context.Background()
id, _, _ := prospects.AddCompany(d, prospects.Company{Name: "Acme", Website: "acme.example", Source: prospects.SourceManual, SignalID: 0}, now)
prospects.AddContact(d, prospects.Contact{CompanyID: id, FirstName: "Kim", LastName: "Ng", Email: "kim@acme.example", Source: prospects.SourceManual}, now)
prospects.Suppress(d, "email", "no@acme.example", "", now)
run, err := FindPeople(ctx, d, h, id, DefaultSettings, now)
if err != nil {
t.Fatal(err)
}
if run.Found != 3 || run.Added != 1 || run.Credits != 1 ||
run.Result != "3 people found, 1 new one, 1 already a prospect, 1 on the suppression list." {
t.Fatalf("run: %+v", run)
}
c, _ := prospects.GetCompany(d, id)
if len(c.Contacts) != 2 {
t.Fatalf("contacts: %+v", c.Contacts)
}
pat, kim := c.Contacts[1], c.Contacts[0]
if pat.Email != "pat@acme.example" || pat.EmailStatus != prospects.EmailValid || pat.Title != "CTO" ||
pat.Source != prospects.SourceHunter || pat.SourceDetail != "Hunter.io, 94% confidence, it" || pat.Status != prospects.StatusNew {
t.Errorf("pat: %+v", pat)
}
if kim.EmailStatus != prospects.EmailRisky || kim.Source != prospects.SourceManual {
t.Errorf("kim (existing) should keep her source and gain a status: %+v", kim)
}
latest, _ := Latest(d, "company:1", "company:9")
if latest["company:1"].Result != run.Result || len(latest) != 1 {
t.Errorf("latest: %+v", latest)
}
other, _, _ := prospects.AddCompany(d, prospects.Company{Name: "Empty", Website: "empty.example", Source: prospects.SourceManual}, now)
if run, err := FindPeople(ctx, d, h, other, DefaultSettings, now); err != nil || run.Result != "Nobody in those roles found at empty.example." {
t.Errorf("empty: %+v %v", run, err)
}
nodomain, _, _ := prospects.AddCompany(d, prospects.Company{Name: "No Site", Source: prospects.SourceManual}, now)
if _, err := FindPeople(ctx, d, h, nodomain, DefaultSettings, now); err == nil || !strings.Contains(err.Error(), "no website") {
t.Errorf("no domain: %v", err)
}
if used, _ := CreditsSince(d, now.Add(-time.Hour)); used != 2 {
t.Errorf("credits used: %v", used)
}
}
func TestFindEmailAndVerify(t *testing.T) {
d := openDB(t)
h := fake(t)
ctx := context.Background()
id, _, _ := prospects.AddCompany(d, prospects.Company{Name: "Acme", Website: "acme.example", Source: prospects.SourceManual}, now)
ann, _, _ := prospects.AddContact(d, prospects.Contact{CompanyID: id, FirstName: "Ann", LastName: "Ray", Source: "origami"}, now)
unk, _, _ := prospects.AddContact(d, prospects.Contact{CompanyID: id, FirstName: "Who", LastName: "Unknown", Source: "origami"}, now)
loose, _, _ := prospects.AddContact(d, prospects.Contact{FirstName: "Lone", LastName: "Wolf", Source: "origami"}, now)
run, err := FindEmail(ctx, d, h, ann, now)
if err != nil || run.Result != "Found ann.ray@acme.example (91% confidence)." || run.Credits != 1 {
t.Fatalf("find: %+v %v", run, err)
}
if p, _ := prospects.GetContact(d, ann); p.Email != "ann.ray@acme.example" || p.EmailStatus != prospects.EmailValid {
t.Errorf("ann: %+v", p)
}
if run, err := FindEmail(ctx, d, h, unk, now); err != nil || run.Result != "No address found at acme.example." || run.Credits != 0 {
t.Errorf("not found: %+v %v", run, err)
}
if _, err := FindEmail(ctx, d, h, loose, now); err == nil || !strings.Contains(err.Error(), "no company") {
t.Errorf("loose: %v", err)
}
if _, err := FindEmail(ctx, d, h, ann, now); err == nil {
t.Error("found an address for someone who has one")
}
pat, _, _ := prospects.AddContact(d, prospects.Contact{CompanyID: id, FirstName: "Pat", Email: "pat@acme.example", Source: prospects.SourceManual}, now)
kim, _, _ := prospects.AddContact(d, prospects.Contact{CompanyID: id, FirstName: "Kim", Email: "kim@acme.example", Source: prospects.SourceManual}, now)
quota, _, _ := prospects.AddContact(d, prospects.Contact{CompanyID: id, FirstName: "Q", Email: "quota@acme.example", Source: prospects.SourceManual}, now)
n, err := VerifyMany(ctx, d, h, []int64{pat, kim, quota, ann}, now)
if n != 2 || !errors.Is(err, hunter.ErrNoCredits) {
t.Fatalf("verify many: %d %v", n, err)
}
for id, want := range map[int64]string{pat: prospects.EmailInvalid, kim: prospects.EmailRisky, quota: "", ann: prospects.EmailValid} {
if p, _ := prospects.GetContact(d, id); p.EmailStatus != want {
t.Errorf("%s: status %q, want %q", p.Email, p.EmailStatus, want)
}
}
latest, _ := Latest(d, prospects.Subject("contact", quota), prospects.Subject("contact", pat))
if !strings.Contains(latest[prospects.Subject("contact", quota)].Error, "credits are used up") ||
latest[prospects.Subject("contact", pat)].Result != "pat@acme.example bounces." {
t.Errorf("latest: %+v", latest)
}
}
func TestSettings(t *testing.T) {
d := openDB(t)
if s := LoadSettings(d); s.PerCompany != 5 || len(s.Departments) != 4 {
t.Errorf("defaults: %+v", s)
}
SaveSettings(d, Settings{Departments: []string{"sales", "bogus", "it"}, Seniority: nil, PerCompany: 0})
if s := LoadSettings(d); strings.Join(s.Departments, ",") != "it,sales" || len(s.Seniority) != 0 || s.PerCompany != 5 {
t.Errorf("saved: %+v", s)
}
}
+66 -1
View File
@@ -29,7 +29,18 @@ var Statuses = []string{StatusNew, StatusAccepted, StatusRejected}
// Where prospects come from. Later parts add discovery, enrichment and
// outside lead sources.
const SourceManual = "manual"
const (
SourceManual = "manual"
SourceHunter = "hunter" // people found by enrichment
)
// Email statuses. Empty means not checked.
const (
EmailValid = "valid"
EmailRisky = "risky" // the server accepts everything, or a personal webmail address
EmailInvalid = "invalid" // bounces, or a disposable address
EmailUnknown = "unknown" // the check couldn't tell
)
// Company is a prospective customer.
type Company struct {
@@ -279,6 +290,52 @@ func AddContact(d *db.DB, c Contact, now time.Time) (id int64, added bool, err e
return id, true, err
}
// SetEmail gives a person an email address found for them, with its
// verification status. It refuses a suppressed address, and one another
// prospect already has. The person's funnel steps get the address too, so
// the CRM and Stripe can be matched to them later.
func SetEmail(d *db.DB, id int64, email, status string) error {
email = strings.ToLower(strings.TrimSpace(email))
if crm.EmailDomain(email) == "" {
return fmt.Errorf("%q isn't an email address", email)
}
if sup, err := IsSuppressed(d, email, ""); err != nil || sup {
if err == nil {
err = fmt.Errorf("%s: %w", email, ErrSuppressed)
}
return err
}
var other int64
err := d.QueryRow(`SELECT id FROM prospect_contacts WHERE email = ? AND id != ?`, email, id).Scan(&other)
if err == nil {
return fmt.Errorf("%s already belongs to another prospect", email)
}
if !errors.Is(err, sql.ErrNoRows) {
return err
}
res, err := d.Exec(`UPDATE prospect_contacts SET email = ?, email_status = ? WHERE id = ?`, email, status, id)
if err != nil {
return err
}
if n, _ := res.RowsAffected(); n == 0 {
return ErrNotFound
}
_, err = d.Exec(`UPDATE funnel_events SET email = ? WHERE subject = ? AND email = ''`, email, Subject("contact", id))
return err
}
// SetEmailStatus records how a person's address checked out.
func SetEmailStatus(d *db.DB, id int64, status string) error {
res, err := d.Exec(`UPDATE prospect_contacts SET email_status = ? WHERE id = ?`, status, id)
if err != nil {
return err
}
if n, _ := res.RowsAffected(); n == 0 {
return ErrNotFound
}
return nil
}
// SetSignal changes the signal a company or person is tagged with (0:
// none), and moves their funnel events with them. A company's people who
// had the company's old signal follow it.
@@ -788,6 +845,14 @@ func SourceLabel(source string) string {
switch source {
case SourceManual:
return "added by hand"
case SourceHunter:
return "Hunter.io"
case signals.SourceOrigami:
return "origami.chat"
case signals.SourceExplee:
return "explee.com"
case "discovery":
return "Claude web search"
}
return source
}
+1 -1
View File
@@ -79,7 +79,7 @@ func TestAcceptQueuesCRMActions(t *testing.T) {
t.Errorf("lead action: %+v", a)
}
desc, _ := a.Fields["description"].(string)
for _, want := range []string{"Source: hunter", "found 21 Nov 2026", "Why it fits: Runs 40 servers", "LinkedIn: https://linkedin.com/in/patlee"} {
for _, want := range []string{"Source: Hunter.io", "found 21 Nov 2026", "Why it fits: Runs 40 servers", "LinkedIn: https://linkedin.com/in/patlee"} {
if !strings.Contains(desc, want) {
t.Errorf("description lacks %q: %s", want, desc)
}
+2
View File
@@ -35,6 +35,8 @@ const (
OrigamiAPIKey = "origami.api_key"
ExpleeAPIKey = "explee.api_key"
HunterAPIKey = "hunter.api_key"
RedditClientID = "reddit.client_id"
RedditClientSecret = "reddit.client_secret"
RedditAccessToken = "reddit.access_token"
+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}}