// Package prospects keeps the companies and people Supermarket found, or // the user added, until the user reviews them. Nothing reaches the CRM // until it's accepted: accepting queues a CRM action that Hermes carries // out. Every prospect records where and when it was found, and the // suppression list is checked before anything is added or queued. package prospects import ( "database/sql" "errors" "fmt" "strconv" "strings" "time" "supermarket/internal/crm" "supermarket/internal/db" "supermarket/internal/signals" ) const ( StatusNew = "new" StatusAccepted = "accepted" StatusRejected = "rejected" ) // Statuses, in the order the review screen's tabs show them. var Statuses = []string{StatusNew, StatusAccepted, StatusRejected} // Where prospects come from. Later parts add discovery, enrichment and // outside lead sources. 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 { ID int64 Name string Domain string Website string LinkedIn string Industry string Size string Location string Why string // why it fits the targets Source string SourceDetail string // a URL or note: where exactly FoundAt time.Time Status string DecidedAt time.Time ActionID int64 CRM CRMState SignalID int64 // the buying signal it was found for; 0: none Contacts []Contact // filled in by Review and GetCompany } // Contact is a person, usually at a prospective company. type Contact struct { ID int64 CompanyID int64 FirstName string LastName string Title string Email string EmailStatus string // '', valid, risky, invalid LinkedIn string Phone string Source string SourceDetail string FoundAt time.Time Status string DecidedAt time.Time ActionID int64 CRM CRMState SignalID int64 } // CRMState is how the CRM action an accepted prospect queued is doing. type CRMState struct { Status string // the crm action's status; '' if none Outcome string EspoID string Error string } // Name is the person's full name, or their email. func (c Contact) Name() string { if n := strings.TrimSpace(c.FirstName + " " + c.LastName); n != "" { return n } return c.Email } // ErrSuppressed means the prospect is on the suppression list. var ErrSuppressed = errors.New("on the suppression list") // ErrNotFound means there's no prospect with that ID. var ErrNotFound = errors.New("no such prospect") const timeFormat = time.RFC3339 func formatTime(t time.Time) string { return t.UTC().Format(timeFormat) } func parseTime(s sql.NullString) time.Time { if !s.Valid { return time.Time{} } t, _ := time.Parse(timeFormat, s.String) return t } func clean(s *string) { *s = strings.TrimSpace(*s) } // --- Adding --- // AddCompany stores a company for review. A company with the same domain // is the same company: its empty fields are filled in from c, and its ID // is returned with added false. A suppressed domain returns ErrSuppressed. func AddCompany(d *db.DB, c Company, now time.Time) (id int64, added bool, err error) { for _, f := range []*string{&c.Name, &c.Website, &c.LinkedIn, &c.Industry, &c.Size, &c.Location, &c.Why, &c.Source, &c.SourceDetail} { clean(f) } if c.Name == "" { return 0, false, errors.New("a company needs a name") } if c.Source == "" { return 0, false, errors.New("a company needs a source") } c.Domain = crm.Domain(c.Domain) if c.Domain == "" { c.Domain = crm.Domain(c.Website) } if c.Website == "" && c.Domain != "" { c.Website = "https://" + c.Domain } else if c.Website != "" && !strings.Contains(c.Website, "://") { c.Website = "https://" + c.Website } if sup, err := IsSuppressed(d, "", c.Domain); err != nil || sup { if err == nil { err = fmt.Errorf("%s: %w", c.Domain, ErrSuppressed) } return 0, false, err } if id, err = findCompany(d, c); err != nil { return 0, false, err } if id != 0 { _, err = d.Exec(`UPDATE prospect_companies SET domain = CASE WHEN domain = '' THEN ? ELSE domain END, website = CASE WHEN website = '' THEN ? ELSE website END, linkedin = CASE WHEN linkedin = '' THEN ? ELSE linkedin END, industry = CASE WHEN industry = '' THEN ? ELSE industry END, size = CASE WHEN size = '' THEN ? ELSE size END, location = CASE WHEN location = '' THEN ? ELSE location END, why = CASE WHEN why = '' THEN ? ELSE why END WHERE id = ?`, c.Domain, c.Website, c.LinkedIn, c.Industry, c.Size, c.Location, c.Why, id) return id, false, err } res, err := d.Exec(`INSERT INTO prospect_companies (name, domain, website, linkedin, industry, size, location, why, source, source_detail, found_at, signal_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, c.Name, c.Domain, c.Website, c.LinkedIn, c.Industry, c.Size, c.Location, c.Why, c.Source, c.SourceDetail, formatTime(now), nullID(c.SignalID)) if err != nil { return 0, false, err } if id, err = res.LastInsertId(); err != nil { return 0, false, err } return id, true, found(d, "company", id, c.SignalID, c.Source, "", now) } func nullID(id int64) any { if id == 0 { return nil } return id } // Subject is how funnel events refer to a prospect. func Subject(kind string, id int64) string { return kind + ":" + strconv.FormatInt(id, 10) } // channelOf is the funnel channel a prospect source belongs to. func channelOf(source string) string { switch source { case signals.SourceOrigami, signals.SourceExplee: return source } return "other" } // found records that a prospect turned up. A company counts once, with its // people; a person on their own counts once. func found(d *db.DB, kind string, id, signalID int64, source, email string, now time.Time) error { _, err := signals.Record(d, signals.Event{ SignalID: signalID, Stage: signals.StageFound, Channel: channelOf(source), Subject: Subject(kind, id), Email: email, Source: signals.SourceSupermarket, ExternalID: "found:" + Subject(kind, id), At: now, }) return err } // AddContact stores a person for review. A contact with the same email is // the same person: their empty fields are filled in and their ID returned // with added false. A suppressed email, or one at a suppressed domain, // returns ErrSuppressed; so does a contact at a suppressed company. func AddContact(d *db.DB, c Contact, now time.Time) (id int64, added bool, err error) { for _, f := range []*string{&c.FirstName, &c.LastName, &c.Title, &c.Email, &c.EmailStatus, &c.LinkedIn, &c.Phone, &c.Source, &c.SourceDetail} { clean(f) } c.Email = strings.ToLower(c.Email) if c.FirstName == "" && c.LastName == "" && c.Email == "" { return 0, false, errors.New("a contact needs a name or an email") } if c.Source == "" { return 0, false, errors.New("a contact needs a source") } if c.Email != "" && !strings.Contains(c.Email, "@") { return 0, false, fmt.Errorf("%q isn't an email address", c.Email) } domain := crm.EmailDomain(c.Email) if c.CompanyID != 0 { var cd string var companySignal int64 if err := d.QueryRow(`SELECT domain, coalesce(signal_id, 0) FROM prospect_companies WHERE id = ?`, c.CompanyID).Scan(&cd, &companySignal); err != nil { if errors.Is(err, sql.ErrNoRows) { return 0, false, ErrNotFound } return 0, false, err } if sup, err := IsSuppressed(d, "", cd); err != nil || sup { if err == nil { err = fmt.Errorf("%s: %w", cd, ErrSuppressed) } return 0, false, err } if c.SignalID == 0 { c.SignalID = companySignal } } if sup, err := IsSuppressed(d, c.Email, domain); err != nil || sup { if err == nil { err = fmt.Errorf("%s: %w", c.Email, ErrSuppressed) } return 0, false, err } var company any if c.CompanyID != 0 { company = c.CompanyID } if id, err = findContact(d, c); err != nil { return 0, false, err } if id != 0 { _, err = d.Exec(`UPDATE prospect_contacts SET company_id = coalesce(company_id, ?), email = CASE WHEN email = '' THEN ? ELSE email END, first_name = CASE WHEN first_name = '' THEN ? ELSE first_name END, last_name = CASE WHEN last_name = '' THEN ? ELSE last_name END, title = CASE WHEN title = '' THEN ? ELSE title END, email_status = CASE WHEN ? != '' THEN ? ELSE email_status END, linkedin = CASE WHEN linkedin = '' THEN ? ELSE linkedin END, phone = CASE WHEN phone = '' THEN ? ELSE phone END WHERE id = ?`, company, c.Email, c.FirstName, c.LastName, c.Title, c.EmailStatus, c.EmailStatus, c.LinkedIn, c.Phone, id) return id, false, err } res, err := d.Exec(`INSERT INTO prospect_contacts (company_id, first_name, last_name, title, email, email_status, linkedin, phone, source, source_detail, found_at, signal_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, company, c.FirstName, c.LastName, c.Title, c.Email, c.EmailStatus, c.LinkedIn, c.Phone, c.Source, c.SourceDetail, formatTime(now), nullID(c.SignalID)) if err != nil { return 0, false, err } if id, err = res.LastInsertId(); err != nil { return 0, false, err } if c.CompanyID == 0 { err = found(d, "contact", id, c.SignalID, c.Source, c.Email, now) } 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. func SetSignal(d *db.DB, kind string, id, signalID int64) error { table, err := table(kind) if err != nil { return err } var old int64 if err := d.QueryRow(`SELECT coalesce(signal_id, 0) FROM `+table+` WHERE id = ?`, id).Scan(&old); err != nil { if errors.Is(err, sql.ErrNoRows) { return ErrNotFound } return err } if _, err := d.Exec(`UPDATE `+table+` SET signal_id = ? WHERE id = ?`, nullID(signalID), id); err != nil { return err } if err := signals.RetagSubject(d, Subject(kind, id), signalID); err != nil { return err } if kind != "company" { return nil } rows, err := d.Query(`SELECT id FROM prospect_contacts WHERE company_id = ? AND coalesce(signal_id, 0) = ?`, id, old) if err != nil { return err } var people []int64 for rows.Next() { var pid int64 if err := rows.Scan(&pid); err != nil { rows.Close() return err } people = append(people, pid) } rows.Close() for _, pid := range people { if err := SetSignal(d, "contact", pid, signalID); err != nil { return err } } return nil } // findCompany is the company already stored as c, or 0: the same domain, // or, when one of them has no domain, the same name. func findCompany(d *db.DB, c Company) (int64, error) { var id int64 q := func(query string, args ...any) error { err := d.QueryRow(query, args...).Scan(&id) if errors.Is(err, sql.ErrNoRows) { return nil } return err } if c.Domain != "" { if err := q(`SELECT id FROM prospect_companies WHERE domain = ?`, c.Domain); err != nil || id != 0 { return id, err } err := q(`SELECT id FROM prospect_companies WHERE domain = '' AND lower(name) = lower(?) ORDER BY id LIMIT 1`, c.Name) return id, err } err := q(`SELECT id FROM prospect_companies WHERE lower(name) = lower(?) ORDER BY domain = '' DESC, id LIMIT 1`, c.Name) return id, err } // normalizeLinkedIn makes profile URLs comparable. func normalizeLinkedIn(u string) string { u = strings.ToLower(strings.TrimSpace(u)) u = strings.TrimPrefix(strings.TrimPrefix(u, "https://"), "http://") u = strings.TrimPrefix(u, "www.") return strings.TrimRight(u, "/") } // findContact is the person already stored as c, or 0: the same email; or, // without one, the same LinkedIn profile; or the same name at the same // company. Tools like origami.chat often have no email for a person. func findContact(d *db.DB, c Contact) (int64, error) { var id int64 q := func(query string, args ...any) error { err := d.QueryRow(query, args...).Scan(&id) if errors.Is(err, sql.ErrNoRows) { return nil } return err } if c.Email != "" { if err := q(`SELECT id FROM prospect_contacts WHERE email = ?`, c.Email); err != nil || id != 0 { return id, err } } if li := normalizeLinkedIn(c.LinkedIn); li != "" { if err := q(`SELECT id FROM prospect_contacts WHERE linkedin != '' AND (email = '' OR ? = '') AND rtrim(replace(replace(replace(lower(linkedin), 'https://', ''), 'http://', ''), 'www.', ''), '/') = ? LIMIT 1`, c.Email, li); err != nil || id != 0 { return id, err } } if c.Email != "" || (c.FirstName == "" && c.LastName == "") { return 0, nil } err := q(`SELECT id FROM prospect_contacts WHERE email = '' AND lower(first_name) = lower(?) AND lower(last_name) = lower(?) AND coalesce(company_id, 0) = ? LIMIT 1`, c.FirstName, c.LastName, c.CompanyID) return id, err } // --- Reading --- const companyColumns = `c.id, c.name, c.domain, c.website, c.linkedin, c.industry, c.size, c.location, c.why, c.source, c.source_detail, c.found_at, c.status, c.decided_at, coalesce(c.action_id, 0), coalesce(a.status, ''), coalesce(a.outcome, ''), coalesce(a.espo_id, ''), coalesce(a.error, ''), coalesce(c.signal_id, 0)` const companyFrom = ` FROM prospect_companies c LEFT JOIN crm_actions a ON a.id = c.action_id` func scanCompanies(rows *sql.Rows) ([]Company, error) { defer rows.Close() var out []Company for rows.Next() { var c Company var found string var decided sql.NullString if err := rows.Scan(&c.ID, &c.Name, &c.Domain, &c.Website, &c.LinkedIn, &c.Industry, &c.Size, &c.Location, &c.Why, &c.Source, &c.SourceDetail, &found, &c.Status, &decided, &c.ActionID, &c.CRM.Status, &c.CRM.Outcome, &c.CRM.EspoID, &c.CRM.Error, &c.SignalID); err != nil { return nil, err } c.FoundAt, _ = time.Parse(timeFormat, found) c.DecidedAt = parseTime(decided) out = append(out, c) } return out, rows.Err() } const contactColumns = `p.id, coalesce(p.company_id, 0), p.first_name, p.last_name, p.title, p.email, p.email_status, p.linkedin, p.phone, p.source, p.source_detail, p.found_at, p.status, p.decided_at, coalesce(p.action_id, 0), coalesce(a.status, ''), coalesce(a.outcome, ''), coalesce(a.espo_id, ''), coalesce(a.error, ''), coalesce(p.signal_id, 0)` const contactFrom = ` FROM prospect_contacts p LEFT JOIN crm_actions a ON a.id = p.action_id` func scanContacts(rows *sql.Rows) ([]Contact, error) { defer rows.Close() var out []Contact for rows.Next() { var c Contact var found string var decided sql.NullString if err := rows.Scan(&c.ID, &c.CompanyID, &c.FirstName, &c.LastName, &c.Title, &c.Email, &c.EmailStatus, &c.LinkedIn, &c.Phone, &c.Source, &c.SourceDetail, &found, &c.Status, &decided, &c.ActionID, &c.CRM.Status, &c.CRM.Outcome, &c.CRM.EspoID, &c.CRM.Error, &c.SignalID); err != nil { return nil, err } c.FoundAt, _ = time.Parse(timeFormat, found) c.DecidedAt = parseTime(decided) out = append(out, c) } return out, rows.Err() } // GetCompany returns a company with all its contacts. func GetCompany(d *db.DB, id int64) (*Company, error) { rows, err := d.Query(`SELECT `+companyColumns+companyFrom+` WHERE c.id = ?`, id) if err != nil { return nil, err } cs, err := scanCompanies(rows) if err != nil { return nil, err } if len(cs) == 0 { return nil, ErrNotFound } rows, err = d.Query(`SELECT `+contactColumns+contactFrom+` WHERE p.company_id = ? ORDER BY p.id`, id) if err != nil { return nil, err } if cs[0].Contacts, err = scanContacts(rows); err != nil { return nil, err } return &cs[0], nil } // GetContact returns one contact. func GetContact(d *db.DB, id int64) (*Contact, error) { rows, err := d.Query(`SELECT `+contactColumns+contactFrom+` WHERE p.id = ?`, id) if err != nil { return nil, err } cs, err := scanContacts(rows) if err != nil { return nil, err } if len(cs) == 0 { return nil, ErrNotFound } return &cs[0], nil } // Review lists what the review screen shows for one status (and one // signal, unless signalID is 0): companies // with that status or with contacts that have it (with only those // contacts), and contacts with that status who aren't at a company. // Newest first. func Review(d *db.DB, status string, signalID int64, limit int) ([]Company, []Contact, error) { rows, err := d.Query(`SELECT `+companyColumns+companyFrom+` WHERE (c.status = ? OR EXISTS (SELECT 1 FROM prospect_contacts p WHERE p.company_id = c.id AND p.status = ?)) AND (? = 0 OR c.signal_id = ?) ORDER BY c.id DESC LIMIT ?`, status, status, signalID, signalID, limit) if err != nil { return nil, nil, err } companies, err := scanCompanies(rows) if err != nil { return nil, nil, err } byID := map[int64]*Company{} ids := make([]string, len(companies)) for i := range companies { byID[companies[i].ID] = &companies[i] ids[i] = strconv.FormatInt(companies[i].ID, 10) } if len(ids) > 0 { // The IDs are integers from the database, so joining them is safe. rows, err := d.Query(`SELECT `+contactColumns+contactFrom+` WHERE p.status = ? AND p.company_id IN (`+strings.Join(ids, ",")+`) ORDER BY p.id`, status) if err != nil { return nil, nil, err } contacts, err := scanContacts(rows) if err != nil { return nil, nil, err } for _, c := range contacts { byID[c.CompanyID].Contacts = append(byID[c.CompanyID].Contacts, c) } } rows, err = d.Query(`SELECT `+contactColumns+contactFrom+` WHERE p.status = ? AND p.company_id IS NULL AND (? = 0 OR p.signal_id = ?) ORDER BY p.id DESC LIMIT ?`, status, signalID, signalID, limit) if err != nil { return nil, nil, err } loose, err := scanContacts(rows) return companies, loose, err } // Counts is how many companies and contacts have each status. func Counts(d *db.DB) (map[string]int, error) { rows, err := d.Query(`SELECT status, count(*) FROM ( SELECT status FROM prospect_companies UNION ALL SELECT status FROM prospect_contacts) GROUP BY status`) if err != nil { return nil, err } defer rows.Close() out := map[string]int{} for rows.Next() { var s string var n int if err := rows.Scan(&s, &n); err != nil { return nil, err } out[s] = n } return out, rows.Err() } // CRMMatches are records already in the CRM (as last synced) that look // like this company: the same website or email domain. func (c *Company) CRMMatches(d *db.DB) ([]crm.Record, error) { if c.Domain == "" { return nil, nil } return crm.Duplicates(d, "", c.Domain) } // CRMMatches are CRM records with this contact's email. func (c *Contact) CRMMatches(d *db.DB) ([]crm.Record, error) { if c.Email == "" { return nil, nil } return crm.Duplicates(d, c.Email, "") } // --- Deciding --- // AcceptCompany queues the company as an EspoCRM Account. func AcceptCompany(d *db.DB, id int64, now time.Time) (*crm.Action, error) { c, err := GetCompany(d, id) if err != nil { return nil, err } if sup, err := IsSuppressed(d, "", c.Domain); err != nil || sup { if err == nil { err = fmt.Errorf("%s: %w", c.Domain, ErrSuppressed) } return nil, err } fields := map[string]any{ "name": c.Name, "description": provenance(c.Source, c.SourceDetail, c.FoundAt, c.Why, companyNotes(c)), } if c.Website != "" { fields["website"] = c.Website } match := map[string]string{"name": c.Name} if c.Website != "" { match = map[string]string{"website": c.Website} } a, err := crm.Enqueue(d, crm.Action{ Key: "prospect-company:" + strconv.FormatInt(id, 10), Entity: "Account", Fields: fields, Match: match, Origin: "prospect-company:" + strconv.FormatInt(id, 10), }) if err != nil { return nil, err } return a, decide(d, "prospect_companies", id, StatusAccepted, a.ID, now) } // AcceptContact queues the person as an EspoCRM Lead, at their company. func AcceptContact(d *db.DB, id int64, now time.Time) (*crm.Action, error) { p, err := GetContact(d, id) if err != nil { return nil, err } var c *Company if p.CompanyID != 0 { if c, err = GetCompany(d, p.CompanyID); err != nil { return nil, err } } domain := crm.EmailDomain(p.Email) if c != nil && c.Domain != "" { if sup, err := IsSuppressed(d, "", c.Domain); err != nil || sup { if err == nil { err = fmt.Errorf("%s: %w", c.Domain, ErrSuppressed) } return nil, err } } if sup, err := IsSuppressed(d, p.Email, domain); err != nil || sup { if err == nil { err = fmt.Errorf("%s: %w", p.Name(), ErrSuppressed) } return nil, err } // EspoCRM requires a last name. last, first := p.LastName, p.FirstName if last == "" { last, first = first, "" } if last == "" { return nil, errors.New("add the person's name first: EspoCRM needs a last name for a Lead") } fields := map[string]any{"firstName": first, "lastName": last, "source": "Other"} set := func(k, v string) { if v != "" { fields[k] = v } } set("title", p.Title) set("emailAddress", p.Email) set("phoneNumber", p.Phone) var why string notes := []string{} if p.LinkedIn != "" { notes = append(notes, "LinkedIn: "+p.LinkedIn) } if p.EmailStatus != "" { notes = append(notes, "Email verification: "+p.EmailStatus) } if c != nil { set("accountName", c.Name) set("website", c.Website) why = c.Why } fields["description"] = provenance(p.Source, p.SourceDetail, p.FoundAt, why, notes) match := map[string]string{"emailAddress": p.Email} if p.Email == "" { match = map[string]string{"firstName": first, "lastName": last} if c != nil { match["accountName"] = c.Name } } key := "prospect-contact:" + strconv.FormatInt(id, 10) a, err := crm.Enqueue(d, crm.Action{Key: key, Entity: "Lead", Fields: fields, Match: match, Origin: key}) if err != nil { return nil, err } return a, decide(d, "prospect_contacts", id, StatusAccepted, a.ID, now) } // AcceptAll accepts a company and its new contacts. func AcceptAll(d *db.DB, id int64, now time.Time) error { c, err := GetCompany(d, id) if err != nil { return err } if c.Status == StatusNew { if _, err := AcceptCompany(d, id, now); err != nil { return err } } for _, p := range c.Contacts { if p.Status == StatusNew { if _, err := AcceptContact(d, p.ID, now); err != nil { return fmt.Errorf("%s: %w", p.Name(), err) } } } return nil } // RejectCompany sets a company and its new contacts aside. func RejectCompany(d *db.DB, id int64, now time.Time) error { if err := decide(d, "prospect_companies", id, StatusRejected, 0, now); err != nil { return err } _, err := d.Exec(`UPDATE prospect_contacts SET status = 'rejected', decided_at = ? WHERE company_id = ? AND status = 'new'`, formatTime(now), id) return err } // RejectContact sets a person aside. func RejectContact(d *db.DB, id int64, now time.Time) error { return decide(d, "prospect_contacts", id, StatusRejected, 0, now) } // Reconsider puts a rejected company or contact back to new. func Reconsider(d *db.DB, kind string, id int64) error { table, err := table(kind) if err != nil { return err } res, err := d.Exec(`UPDATE `+table+` SET status = 'new', decided_at = NULL WHERE id = ? AND status = 'rejected'`, id) if err != nil { return err } if n, _ := res.RowsAffected(); n == 0 { return ErrNotFound } return nil } func table(kind string) (string, error) { switch kind { case "company": return "prospect_companies", nil case "contact": return "prospect_contacts", nil } return "", fmt.Errorf("unknown kind %q", kind) } // decide records a decision; actionID 0 keeps the current one. func decide(d *db.DB, table string, id int64, status string, actionID int64, now time.Time) error { var action any if actionID != 0 { action = actionID } res, err := d.Exec(`UPDATE `+table+` SET status = ?, decided_at = ?, action_id = coalesce(?, action_id) WHERE id = ?`, status, formatTime(now), action, id) if err != nil { return err } if n, _ := res.RowsAffected(); n == 0 { return ErrNotFound } return nil } func companyNotes(c *Company) []string { var notes []string for _, f := range []struct{ label, v string }{ {"Industry", c.Industry}, {"Size", c.Size}, {"Location", c.Location}, {"LinkedIn", c.LinkedIn}, } { if f.v != "" { notes = append(notes, f.label+": "+f.v) } } return notes } // provenance is the CRM record's description: where and when the prospect // was found, and why it fits. func provenance(source, detail string, found time.Time, why string, notes []string) string { var b strings.Builder b.WriteString("Added by Supermarket. Source: " + SourceLabel(source)) if detail != "" { b.WriteString(" (" + detail + ")") } b.WriteString(", found " + found.Format("2 Jan 2006") + ".") if why != "" { b.WriteString("\nWhy it fits: " + why) } for _, n := range notes { b.WriteString("\n" + n) } return b.String() } // SourceLabel is how a source is shown. 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 } // --- Suppression list --- // Suppression is one entry on the list: an email or a whole domain. type Suppression struct { Kind string // email or domain Value string Reason string CreatedAt time.Time } // normalize checks a suppression's kind and value; a value with @ is an // email whatever the kind says, and a domain may be given as a URL. func normalize(kind, value string) (string, string, error) { value = strings.ToLower(strings.TrimSpace(value)) if strings.Contains(value, "@") { kind = "email" } switch kind { case "email": if crm.EmailDomain(value) == "" { return "", "", fmt.Errorf("%q isn't an email address", value) } case "domain", "": kind = "domain" value = crm.Domain(value) if !strings.Contains(value, ".") { return "", "", errors.New("give an email address or a domain, like example.com") } default: return "", "", fmt.Errorf("unknown kind %q", kind) } return kind, value, nil } // Suppress adds an email or domain to the suppression list. Prospects it // covers that are still new are rejected; accepted ones aren't touched, // since they may already be in the CRM. func Suppress(d *db.DB, kind, value, reason string, now time.Time) error { kind, value, err := normalize(kind, value) if err != nil { return err } if _, err := d.Exec(`INSERT INTO suppressions (kind, value, reason) VALUES (?, ?, ?) ON CONFLICT (kind, value) DO UPDATE SET reason = CASE WHEN excluded.reason != '' THEN excluded.reason ELSE reason END`, kind, value, strings.TrimSpace(reason)); err != nil { return err } at := formatTime(now) if kind == "email" { _, err = d.Exec(`UPDATE prospect_contacts SET status = 'rejected', decided_at = ? WHERE email = ? AND status = 'new'`, at, value) return err } if _, err := d.Exec(`UPDATE prospect_contacts SET status = 'rejected', decided_at = ? WHERE status = 'new' AND ( email LIKE '%@' || ? OR company_id IN (SELECT id FROM prospect_companies WHERE domain = ?))`, at, value, value); err != nil { return err } _, err = d.Exec(`UPDATE prospect_companies SET status = 'rejected', decided_at = ? WHERE domain = ? AND status = 'new'`, at, value) return err } // Unsuppress takes an entry off the list. func Unsuppress(d *db.DB, kind, value string) error { kind, value, err := normalize(kind, value) if err != nil { return err } _, err = d.Exec(`DELETE FROM suppressions WHERE kind = ? AND value = ?`, kind, value) return err } // Suppressions is the whole list, newest first. func Suppressions(d *db.DB) ([]Suppression, error) { rows, err := d.Query(`SELECT kind, value, reason, created_at FROM suppressions ORDER BY created_at DESC, value`) if err != nil { return nil, err } defer rows.Close() var out []Suppression for rows.Next() { var s Suppression var at string if err := rows.Scan(&s.Kind, &s.Value, &s.Reason, &at); err != nil { return nil, err } s.CreatedAt, _ = time.Parse(timeFormat, at) out = append(out, s) } return out, rows.Err() } // IsSuppressed reports whether an email, or a domain, is on the list. The // email's own domain counts too. func IsSuppressed(d *db.DB, email, domain string) (bool, error) { email = strings.ToLower(strings.TrimSpace(email)) domain = crm.Domain(domain) emailDomain := crm.EmailDomain(email) var n int err := d.QueryRow(`SELECT count(*) FROM suppressions WHERE (kind = 'email' AND ? != '' AND value = ?) OR (kind = 'domain' AND value IN (?, ?) AND value != '')`, email, email, domain, emailDomain).Scan(&n) return n > 0, err } // --- Search --- // matchAll is a condition that every (lower-case) word appears in one of // the columns, and its arguments. func matchAll(words []string, columns ...string) (string, []any) { hay := "lower(" + strings.Join(columns, " || ' ' || ") + ")" conds := make([]string, 0, len(words)) args := make([]any, 0, len(words)) for _, w := range words { conds = append(conds, "instr("+hay+", ?) > 0") args = append(args, w) } return strings.Join(conds, " AND "), args } // Search finds companies and contacts containing every word, newest first. func Search(d *db.DB, words []string, limit int) ([]Company, []Contact, error) { if len(words) == 0 { return nil, nil, nil } cond, args := matchAll(words, "c.name", "c.domain", "c.industry", "c.location", "c.why") rows, err := d.Query(`SELECT `+companyColumns+companyFrom+` WHERE `+cond+` ORDER BY c.id DESC LIMIT ?`, append(args, limit)...) if err != nil { return nil, nil, err } companies, err := scanCompanies(rows) if err != nil { return nil, nil, err } cond, args = matchAll(words, "p.first_name", "p.last_name", "p.title", "p.email", "coalesce((SELECT name FROM prospect_companies WHERE id = p.company_id), '')") rows, err = d.Query(`SELECT `+contactColumns+contactFrom+` WHERE `+cond+` ORDER BY p.id DESC LIMIT ?`, append(args, limit)...) if err != nil { return nil, nil, err } contacts, err := scanContacts(rows) return companies, contacts, err } // Delete forgets a company (with its people) or a person added by mistake: // their steps in the funnel and Hunter.io searches go too, and a CRM action // that hasn't been done yet is taken back. A record Hermes already added to // EspoCRM stays there. func Delete(d *db.DB, kind string, id int64) error { tbl, err := table(kind) if err != nil { return err } tx, err := d.Begin() if err != nil { return err } defer tx.Rollback() var exists int if err := tx.QueryRow(`SELECT count(*) FROM `+tbl+` WHERE id = ?`, id).Scan(&exists); err != nil { return err } if exists == 0 { return ErrNotFound } contacts := []int64{} if kind == "contact" { contacts = append(contacts, id) } else { rows, err := tx.Query(`SELECT id FROM prospect_contacts WHERE company_id = ?`, id) if err != nil { return err } for rows.Next() { var c int64 if err := rows.Scan(&c); err != nil { rows.Close() return err } contacts = append(contacts, c) } rows.Close() } subjects := []any{} if kind == "company" { subjects = append(subjects, "company:"+strconv.FormatInt(id, 10)) } for _, c := range contacts { subjects = append(subjects, "contact:"+strconv.FormatInt(c, 10)) } origins := make([]any, len(subjects)) for i, s := range subjects { origins[i] = "prospect-" + s.(string) } in := "(?" + strings.Repeat(", ?", len(subjects)-1) + ")" for _, q := range []struct { sql string args []any }{ {`DELETE FROM funnel_events WHERE subject IN ` + in, subjects}, {`DELETE FROM enrich_runs WHERE subject IN ` + in, subjects}, {`UPDATE crm_actions SET status = 'cancelled' WHERE status IN ('pending', 'failed') AND origin IN ` + in, origins}, } { if _, err := tx.Exec(q.sql, q.args...); err != nil { return err } } for _, c := range contacts { if _, err := tx.Exec(`DELETE FROM prospect_contacts WHERE id = ?`, c); err != nil { return err } } if kind == "company" { if _, err := tx.Exec(`DELETE FROM prospect_companies WHERE id = ?`, id); err != nil { return err } } return tx.Commit() }