Files
supermarket/internal/enrich/enrich.go
T
davidandClaude Opus 5.5 1b2947de7c Phase 9, part 2: one database layer for SQLite and Postgres
db.DB wraps database/sql for either database. The SQL stays SQLite's: on
Postgres each statement's ? become $n and LIKE ignores case as SQLite's
does, and the Postgres schema (postgres.sql, schema 29 as a whole) adds
SQLite's instr, json_extract and two-argument max/min, and a nocase ICU
collation. Needs Postgres 18.

LastInsertId became db.Insert (RETURNING id), INSERT OR IGNORE became ON
CONFLICT DO NOTHING, upserts qualify their columns, and three queries
group by every column they use. SUPERMARKET_TEST_POSTGRES runs the test
suite on Postgres, a new schema per test; all tests pass on both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 07:10:44 -07:00

385 lines
11 KiB
Go

// 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 {
newID, err := d.Insert(`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 = newID
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
}