diff --git a/PLAN.md b/PLAN.md index 5fd9de4..1a11fc2 100644 --- a/PLAN.md +++ b/PLAN.md @@ -480,7 +480,15 @@ read sync, CRM queue page, proved with one test Lead; (2) prospects and the review screen, dedupe, suppression list, provenance; (3) discovery; (4) enrichment with Hunter; (5) outside lead sources (CSV, then origami.chat / explee.com); (6) intent signals on X (Reddit after API -approval). +approval). Part 1 is +committed (1dc5476); its live test waits on the Core's MCP hub, which +connects to EspoCRM at a stale LAN address. Part 2 is built: the +`prospects` package (companies, contacts, merged by domain and email), +Prospects → Review (accept a company → Account, a person → Lead, both with +provenance in the description; set aside; reconsider; CRM-duplicate +warnings from the last sync), adding prospects by hand, the suppression +list (emails and domains, checked on add and before queueing), and +prospects in Search. 1. Discovery from the profile's targets, from these sources: - company search (enrichment provider, Brave Search API) diff --git a/README.md b/README.md index 8fa4847..f46b1f1 100644 --- a/README.md +++ b/README.md @@ -94,6 +94,8 @@ Hermes' sandbox can only reach the hub once it's in `network.allowedDomains` in To check the connection, open **Core & Hermes** in Supermarket and ask Hermes the question shown there. Hermes lists the hub's tools and reports them back to Supermarket, which shows when it last heard from Hermes. +**Prospects (Prospects → Review).** Companies and people who may fit your targets wait here for review; for now you add them by hand, and finding them for you comes next. Each keeps where and when it was found. Accepting a company queues an EspoCRM Account, accepting a person queues a Lead at their company, with the source, date and why they fit in the record's description. Before you decide, the page warns about records already in your CRM (as of the last sync). *Set aside* keeps a prospect out of the way; the **suppression list** (Prospects → Suppression list) holds emails and domains that must never be added, and is checked when a prospect is added and again before anything is queued. + **The CRM queue (Prospects → CRM queue).** What Supermarket wants in EspoCRM waits in a queue, with the exact fields and how to recognise a record that's already there. `supermarket hermes` adds a Hermes scheduled job, `supermarket-crm`, that runs every 15 minutes: it calls Supermarket's `crm_pending_actions` tool, creates each record through the hub's EspoCRM tools unless a matching one exists, and reports each result with `crm_report_result`. Every 6 hours (or when you press *Sync on the next run*) it also copies your Leads, Accounts and Contacts to Supermarket with `crm_ingest`, so Supermarket can spot people and companies you already have. Before each run, the job runs `~/.hermes/scripts/supermarket-crm-check.sh`, which prints `crm-state` from the data folder; while that hasn't changed, Hermes skips the run and uses no AI. The page shows the command to run the job now, and *Send a test Lead* checks the whole path. Failed actions can be retried or cancelled; nothing is written to your CRM that isn't in the queue. ## Writing and publishing posts diff --git a/internal/db/db.go b/internal/db/db.go index b7d6432..865bab1 100644 --- a/internal/db/db.go +++ b/internal/db/db.go @@ -166,6 +166,60 @@ CREATE TABLE crm_records ( ); CREATE INDEX crm_records_by_email ON crm_records (email); CREATE INDEX crm_records_by_domain ON crm_records (domain); +`, + // 6: prospects. Companies and people Supermarket found (or the user + // added), waiting for review; nothing reaches the CRM until accepted. + // Every one records where and when it was found. + ` +CREATE TABLE prospect_companies ( + id INTEGER PRIMARY KEY, + name TEXT NOT NULL, + domain TEXT NOT NULL DEFAULT '' COLLATE NOCASE, -- one company per domain + website TEXT NOT NULL DEFAULT '', + linkedin TEXT NOT NULL DEFAULT '', + industry TEXT NOT NULL DEFAULT '', + size TEXT NOT NULL DEFAULT '', + location TEXT NOT NULL DEFAULT '', + why TEXT NOT NULL DEFAULT '', -- why it fits the targets + source TEXT NOT NULL, -- manual, discovery, hunter, csv… + source_detail TEXT NOT NULL DEFAULT '', -- a URL or note: where exactly + found_at TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'new', -- new, accepted, rejected + decided_at TEXT, + action_id INTEGER -- the CRM action that adds it as an Account +); +CREATE UNIQUE INDEX prospect_companies_by_domain ON prospect_companies (domain) WHERE domain != ''; +CREATE INDEX prospect_companies_by_status ON prospect_companies (status, id); + +CREATE TABLE prospect_contacts ( + id INTEGER PRIMARY KEY, + company_id INTEGER REFERENCES prospect_companies (id) ON DELETE SET NULL, + first_name TEXT NOT NULL DEFAULT '', + last_name TEXT NOT NULL DEFAULT '', + title TEXT NOT NULL DEFAULT '', + email TEXT NOT NULL DEFAULT '' COLLATE NOCASE, -- one contact per email + email_status TEXT NOT NULL DEFAULT '', -- '', valid, risky, invalid (from verification) + linkedin TEXT NOT NULL DEFAULT '', + phone TEXT NOT NULL DEFAULT '', + source TEXT NOT NULL, + source_detail TEXT NOT NULL DEFAULT '', + found_at TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'new', -- new, accepted, rejected + decided_at TEXT, + action_id INTEGER -- the CRM action that adds them as a Lead +); +CREATE UNIQUE INDEX prospect_contacts_by_email ON prospect_contacts (email) WHERE email != ''; +CREATE INDEX prospect_contacts_by_company ON prospect_contacts (company_id); + +-- People and companies who must never be contacted or added: checked +-- before anything is found, shown or queued. +CREATE TABLE suppressions ( + kind TEXT NOT NULL, -- email or domain + value TEXT NOT NULL COLLATE NOCASE, + reason TEXT NOT NULL DEFAULT '', + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')), + PRIMARY KEY (kind, value) +); `, } diff --git a/internal/prospects/prospects.go b/internal/prospects/prospects.go new file mode 100644 index 0000000..ce7b27b --- /dev/null +++ b/internal/prospects/prospects.go @@ -0,0 +1,782 @@ +// 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" +) + +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" + +// 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 + + 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 +} + +// 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 c.Domain != "" { + err := d.QueryRow(`SELECT id FROM prospect_companies WHERE domain = ?`, c.Domain).Scan(&id) + if err == nil { + _, err = d.Exec(`UPDATE prospect_companies SET + 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.Website, c.LinkedIn, c.Industry, c.Size, c.Location, c.Why, id) + return id, false, err + } + if !errors.Is(err, sql.ErrNoRows) { + return 0, false, err + } + } + res, err := d.Exec(`INSERT INTO prospect_companies (name, domain, website, linkedin, industry, size, location, why, + source, source_detail, found_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + c.Name, c.Domain, c.Website, c.LinkedIn, c.Industry, c.Size, c.Location, c.Why, c.Source, c.SourceDetail, formatTime(now)) + if err != nil { + return 0, false, err + } + id, err = res.LastInsertId() + return id, true, 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 + if err := d.QueryRow(`SELECT domain FROM prospect_companies WHERE id = ?`, c.CompanyID).Scan(&cd); 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 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 c.Email != "" { + err := d.QueryRow(`SELECT id FROM prospect_contacts WHERE email = ?`, c.Email).Scan(&id) + if err == nil { + _, err = d.Exec(`UPDATE prospect_contacts SET + company_id = coalesce(company_id, ?), + 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.FirstName, c.LastName, c.Title, c.EmailStatus, c.EmailStatus, c.LinkedIn, c.Phone, id) + return id, false, err + } + if !errors.Is(err, sql.ErrNoRows) { + return 0, 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) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + company, c.FirstName, c.LastName, c.Title, c.Email, c.EmailStatus, c.LinkedIn, c.Phone, c.Source, c.SourceDetail, formatTime(now)) + if err != nil { + return 0, false, err + } + id, err = res.LastInsertId() + return id, true, 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, '')` + +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); 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, '')` + +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); 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: 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, 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 = ?) + ORDER BY c.id DESC LIMIT ?`, status, status, 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 ORDER BY p.id DESC LIMIT ?`, status, 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" + } + 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 +} diff --git a/internal/prospects/prospects_test.go b/internal/prospects/prospects_test.go new file mode 100644 index 0000000..bb3e863 --- /dev/null +++ b/internal/prospects/prospects_test.go @@ -0,0 +1,220 @@ +package prospects + +import ( + "errors" + "path/filepath" + "strconv" + "strings" + "testing" + "time" + + "supermarket/internal/crm" + "supermarket/internal/db" +) + +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 +} + +var now = time.Date(2026, 11, 21, 15, 0, 0, 0, time.UTC) + +func TestAddMergesByDomainAndEmail(t *testing.T) { + d := openDB(t) + id, added, err := AddCompany(d, Company{Name: "Acme", Website: "https://www.Acme.com/about", Source: SourceManual}, now) + if err != nil || !added { + t.Fatalf("add: %v %v", added, err) + } + id2, added, err := AddCompany(d, Company{Name: "Acme Inc", Domain: "acme.com", Industry: "Widgets", Source: "discovery"}, now) + if err != nil || added || id2 != id { + t.Fatalf("same domain: %d %v %v", id2, added, err) + } + c, err := GetCompany(d, id) + if err != nil || c.Name != "Acme" || c.Domain != "acme.com" || c.Industry != "Widgets" || c.Source != SourceManual || c.Status != StatusNew { + t.Fatalf("merged company: %+v %v", c, err) + } + + pid, _, err := AddContact(d, Contact{CompanyID: id, FirstName: "Pat", Email: "Pat@Acme.com", Source: SourceManual}, now) + if err != nil { + t.Fatal(err) + } + pid2, added, err := AddContact(d, Contact{LastName: "Lee", Title: "CTO", Email: "pat@acme.com", EmailStatus: "valid", Source: "hunter"}, now) + if err != nil || added || pid2 != pid { + t.Fatalf("same email: %d %v %v", pid2, added, err) + } + p, _ := GetContact(d, pid) + if p.Name() != "Pat Lee" || p.Title != "CTO" || p.EmailStatus != "valid" || p.CompanyID != id { + t.Fatalf("merged contact: %+v", p) + } + if _, _, err := AddContact(d, Contact{Email: "not-an-email", Source: SourceManual}, now); err == nil { + t.Error("bad email accepted") + } + if _, _, err := AddCompany(d, Company{Name: "No source"}, now); err == nil { + t.Error("a company without a source was accepted") + } +} + +func TestAcceptQueuesCRMActions(t *testing.T) { + d := openDB(t) + cid, _, _ := AddCompany(d, Company{Name: "Acme", Website: "acme.com", Why: "Runs 40 servers", Source: "discovery", + SourceDetail: "https://news.example/acme"}, now) + pid, _, _ := AddContact(d, Contact{CompanyID: cid, FirstName: "Pat", LastName: "Lee", Title: "CTO", Email: "pat@acme.com", + LinkedIn: "https://linkedin.com/in/patlee", Source: "hunter"}, now) + noName, _, _ := AddContact(d, Contact{CompanyID: cid, Email: "info@acme.com", Source: "hunter"}, now) + + if _, err := AcceptContact(d, noName, now); err == nil || !strings.Contains(err.Error(), "last name") { + t.Errorf("a contact without a name: %v", err) + } + a, err := AcceptContact(d, pid, now) + if err != nil { + t.Fatal(err) + } + if a.Entity != "Lead" || a.Fields["accountName"] != "Acme" || a.Fields["emailAddress"] != "pat@acme.com" || + a.Match["emailAddress"] != "pat@acme.com" || a.Origin != "prospect-contact:"+itoa(pid) { + 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"} { + if !strings.Contains(desc, want) { + t.Errorf("description lacks %q: %s", want, desc) + } + } + // Accepting twice doesn't queue twice. + if b, _ := AcceptContact(d, pid, now); b.ID != a.ID { + t.Error("accepting twice queued another action") + } + + acc, err := AcceptCompany(d, cid, now) + if err != nil || acc.Entity != "Account" || acc.Fields["website"] != "https://acme.com" || acc.Match["website"] != "https://acme.com" { + t.Fatalf("account action: %+v %v", acc, err) + } + p, _ := GetContact(d, pid) + if p.Status != StatusAccepted || p.ActionID != a.ID || p.CRM.Status != crm.StatusPending { + t.Errorf("accepted contact: %+v", p) + } + + // The CRM's result shows on the prospect. + crm.Claim(d, now, 10) + crm.Report(d, a.ID, crm.Result{Outcome: "created", EspoID: "abc"}, now) + p, _ = GetContact(d, pid) + if p.CRM.Status != crm.StatusDone || p.CRM.EspoID != "abc" { + t.Errorf("crm state: %+v", p.CRM) + } +} + +func TestReviewAndReject(t *testing.T) { + d := openDB(t) + cid, _, _ := AddCompany(d, Company{Name: "Acme", Domain: "acme.com", Source: SourceManual}, now) + p1, _, _ := AddContact(d, Contact{CompanyID: cid, LastName: "One", Source: SourceManual}, now) + p2, _, _ := AddContact(d, Contact{CompanyID: cid, LastName: "Two", Source: SourceManual}, now) + loose, _, _ := AddContact(d, Contact{LastName: "Loose", Email: "l@else.org", Source: SourceManual}, now) + + cs, ps, err := Review(d, StatusNew, 50) + if err != nil || len(cs) != 1 || len(cs[0].Contacts) != 2 || len(ps) != 1 || ps[0].ID != loose { + t.Fatalf("new: %+v %+v %v", cs, ps, err) + } + AcceptContact(d, p1, now) + cs, _, _ = Review(d, StatusAccepted, 50) + if len(cs) != 1 || len(cs[0].Contacts) != 1 || cs[0].Contacts[0].ID != p1 { + t.Errorf("accepted tab: %+v", cs) + } + if err := RejectCompany(d, cid, now); err != nil { + t.Fatal(err) + } + if p, _ := GetContact(d, p2); p.Status != StatusRejected { + t.Error("rejecting the company should reject its new contacts") + } + if p, _ := GetContact(d, p1); p.Status != StatusAccepted { + t.Error("rejecting the company shouldn't touch accepted contacts") + } + if err := Reconsider(d, "contact", p2); err != nil { + t.Fatal(err) + } + if p, _ := GetContact(d, p2); p.Status != StatusNew { + t.Error("reconsider") + } + counts, _ := Counts(d) + if counts[StatusNew] != 2 || counts[StatusAccepted] != 1 || counts[StatusRejected] != 1 { + t.Errorf("counts: %v", counts) + } + if err := AcceptAll(d, cid, now); err != nil { + t.Fatal(err) + } + if p, _ := GetContact(d, p2); p.Status != StatusAccepted { + t.Error("accept all") + } +} + +func TestSuppression(t *testing.T) { + d := openDB(t) + cid, _, _ := AddCompany(d, Company{Name: "Acme", Domain: "acme.com", Source: SourceManual}, now) + pid, _, _ := AddContact(d, Contact{CompanyID: cid, LastName: "Lee", Email: "pat@acme.com", Source: SourceManual}, now) + other, _, _ := AddContact(d, Contact{LastName: "Ray", Email: "ray@gmail.com", Source: SourceManual}, now) + + if err := Suppress(d, "", "nope", "", now); err == nil { + t.Error("a bad value was accepted") + } + if err := Suppress(d, "", "Ray@Gmail.com", "asked not to be contacted", now); err != nil { + t.Fatal(err) + } + if p, _ := GetContact(d, other); p.Status != StatusRejected { + t.Error("a suppressed email should be rejected") + } + if _, err := AcceptContact(d, other, now); !errors.Is(err, ErrSuppressed) { + t.Errorf("accepting a suppressed contact: %v", err) + } + if _, _, err := AddContact(d, Contact{LastName: "Ray", Email: "ray@gmail.com", Source: "hunter"}, now); !errors.Is(err, ErrSuppressed) { + t.Errorf("re-adding a suppressed contact: %v", err) + } + // Free mail: suppressing one address doesn't suppress gmail.com. + if sup, _ := IsSuppressed(d, "someone@gmail.com", ""); sup { + t.Error("one gmail address suppressed all of gmail") + } + + if err := Suppress(d, "domain", "https://www.acme.com", "existing customer", now); err != nil { + t.Fatal(err) + } + if c, _ := GetCompany(d, cid); c.Status != StatusRejected || c.Contacts[0].Status != StatusRejected { + t.Errorf("suppressed domain: %+v", c) + } + if _, _, err := AddContact(d, Contact{LastName: "New", Email: "new@acme.com", Source: "hunter"}, now); !errors.Is(err, ErrSuppressed) { + t.Errorf("a contact at a suppressed domain: %v", err) + } + if _, err := AcceptContact(d, pid, now); !errors.Is(err, ErrSuppressed) { + t.Errorf("accepting at a suppressed domain: %v", err) + } + list, _ := Suppressions(d) + if len(list) != 2 { + t.Fatalf("list: %+v", list) + } + if err := Unsuppress(d, "domain", "acme.com"); err != nil { + t.Fatal(err) + } + if sup, _ := IsSuppressed(d, "pat@acme.com", ""); sup { + t.Error("unsuppress") + } +} + +func TestCRMMatches(t *testing.T) { + d := openDB(t) + rec, _ := crm.RecordFrom("Account", map[string]any{"id": "a1", "name": "Acme", "website": "acme.com"}, now) + lead, _ := crm.RecordFrom("Lead", map[string]any{"id": "l1", "firstName": "Pat", "lastName": "Lee", "emailAddress": "pat@acme.com"}, now) + crm.Ingest(d, []crm.Record{rec, lead}) + cid, _, _ := AddCompany(d, Company{Name: "Acme Corp", Website: "https://acme.com", Source: SourceManual}, now) + c, _ := GetCompany(d, cid) + if m, _ := c.CRMMatches(d); len(m) != 2 { + t.Errorf("company matches: %+v", m) + } + pid, _, _ := AddContact(d, Contact{LastName: "Lee", Email: "PAT@acme.com", Source: SourceManual}, now) + p, _ := GetContact(d, pid) + if m, _ := p.CRMMatches(d); len(m) != 1 || m[0].EspoID != "l1" { + t.Errorf("contact matches: %+v", m) + } +} + +func itoa(n int64) string { return strconv.FormatInt(n, 10) } diff --git a/internal/web/prospects.go b/internal/web/prospects.go new file mode 100644 index 0000000..a33826f --- /dev/null +++ b/internal/web/prospects.go @@ -0,0 +1,282 @@ +package web + +import ( + "errors" + "net/http" + "strconv" + "strings" + "time" + + "supermarket/internal/crm" + "supermarket/internal/prospects" +) + +// newProspects is how many companies and people wait for review. +func (s *Server) newProspects() int { + counts, err := prospects.Counts(s.DB) + if err != nil { + s.Log.Error("counting prospects", "err", err) + } + return counts[prospects.StatusNew] +} + +// reviewTab is the status a request asks for, new by default. +func reviewTab(v string) string { + for _, st := range prospects.Statuses { + if v == st { + return v + } + } + return prospects.StatusNew +} + +func (s *Server) prospectsPage(w http.ResponseWriter, r *http.Request) { + s.renderProspects(w, r, reviewTab(r.URL.Query().Get("status")), "") +} + +func (s *Server) renderProspects(w http.ResponseWriter, r *http.Request, tab, errMsg string) { + companies, loose, err := prospects.Review(s.DB, tab, 200) + if err != nil { + s.serverError(w, err) + return + } + counts, err := prospects.Counts(s.DB) + if err != nil { + s.serverError(w, err) + return + } + // Records already in the CRM that look like each prospect, from the + // last sync. Only worth showing before a decision. + matches := map[string][]crm.Record{} + if tab == prospects.StatusNew { + for i := range companies { + c := &companies[i] + if m, err := c.CRMMatches(s.DB); err == nil && len(m) > 0 { + matches["company:"+strconv.FormatInt(c.ID, 10)] = m + } + for j := range c.Contacts { + p := &c.Contacts[j] + if m, err := p.CRMMatches(s.DB); err == nil && len(m) > 0 { + matches["contact:"+strconv.FormatInt(p.ID, 10)] = m + } + } + } + for i := range loose { + if m, err := loose[i].CRMMatches(s.DB); err == nil && len(m) > 0 { + matches["contact:"+strconv.FormatInt(loose[i].ID, 10)] = m + } + } + } + sync, err := crm.LoadSync(s.DB) + if err != nil { + s.serverError(w, err) + return + } + s.render(w, r, "prospects", page{Title: "Review prospects", Nav: "prospects/review", Error: errMsg, Data: map[string]any{ + "Tab": tab, + "Statuses": prospects.Statuses, + "Counts": counts, + "Companies": companies, + "Loose": loose, + "Matches": matches, + "Synced": sync.Last, + }}) +} + +// prospectAction handles the review screen's buttons. +func (s *Server) prospectAction(w http.ResponseWriter, r *http.Request) { + kind, action := r.PathValue("kind"), r.PathValue("action") + id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) + if err != nil || (kind != "company" && kind != "contact") { + http.NotFound(w, r) + return + } + if err := r.ParseForm(); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + tab := reviewTab(r.PostFormValue("tab")) + now := time.Now() + var msg string + switch kind + "/" + action { + case "company/accept": + err, msg = ignore(prospects.AcceptCompany(s.DB, id, now)), "accepted" + case "company/accept-all": + err, msg = prospects.AcceptAll(s.DB, id, now), "accepted" + case "contact/accept": + err, msg = ignore(prospects.AcceptContact(s.DB, id, now)), "accepted" + case "company/reject": + err, msg = prospects.RejectCompany(s.DB, id, now), "rejected" + case "contact/reject": + err, msg = prospects.RejectContact(s.DB, id, now), "rejected" + case "company/reconsider", "contact/reconsider": + err, msg = prospects.Reconsider(s.DB, kind, id), "reconsidered" + case "company/suppress": + c, gerr := prospects.GetCompany(s.DB, id) + if err = gerr; err == nil { + if c.Domain == "" { + err = errors.New(c.Name + " has no website, so there's no domain to suppress") + } else { + err = prospects.Suppress(s.DB, "domain", c.Domain, r.PostFormValue("reason"), now) + } + } + msg = "suppressed" + case "contact/suppress": + p, gerr := prospects.GetContact(s.DB, id) + if err = gerr; err == nil { + if p.Email == "" { + err = errors.New(p.Name() + " has no email address to suppress") + } else { + err = prospects.Suppress(s.DB, "email", p.Email, r.PostFormValue("reason"), now) + } + } + msg = "suppressed" + default: + http.NotFound(w, r) + return + } + if errors.Is(err, prospects.ErrNotFound) { + http.NotFound(w, r) + return + } + if err != nil { + s.renderProspects(w, r, tab, "Couldn't do that: "+err.Error()) + return + } + redirect(w, r, "/prospects?status="+tab, msg) +} + +// ignore drops a result and keeps the error. +func ignore[T any](_ T, err error) error { return err } + +// --- Adding by hand --- + +type prospectFormData struct { + Company prospects.Company + Contact prospects.Contact + CompanyID int64 // adding a person at a company already in review + Companies []prospects.Company + For string // that company's name +} + +func (s *Server) prospectForm(w http.ResponseWriter, r *http.Request) { + d := prospectFormData{} + if id, err := strconv.ParseInt(r.URL.Query().Get("company"), 10, 64); err == nil { + c, err := prospects.GetCompany(s.DB, id) + if err != nil { + http.NotFound(w, r) + return + } + d.CompanyID, d.For = c.ID, c.Name + } + s.render(w, r, "prospect-new", page{Title: "Add a prospect", Nav: "prospects/review", Data: d}) +} + +func (s *Server) prospectAdd(w http.ResponseWriter, r *http.Request) { + if err := r.ParseForm(); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + f := r.PostFormValue + now := time.Now() + d := prospectFormData{ + Company: prospects.Company{ + Name: f("company_name"), Website: f("website"), LinkedIn: f("company_linkedin"), + Industry: f("industry"), Size: f("size"), Location: f("location"), Why: f("why"), + Source: prospects.SourceManual, SourceDetail: f("source_detail"), + }, + Contact: prospects.Contact{ + FirstName: f("first_name"), LastName: f("last_name"), Title: f("title"), Email: f("email"), + LinkedIn: f("linkedin"), Phone: f("phone"), + Source: prospects.SourceManual, SourceDetail: f("source_detail"), + }, + } + d.CompanyID, _ = strconv.ParseInt(f("company_id"), 10, 64) + if d.CompanyID != 0 { + c, err := prospects.GetCompany(s.DB, d.CompanyID) + if err != nil { + http.NotFound(w, r) + return + } + d.For = c.Name + } + fail := func(msg string) { + s.render(w, r, "prospect-new", page{Title: "Add a prospect", Nav: "prospects/review", Error: msg, Data: d}) + } + hasCompany := strings.TrimSpace(d.Company.Name) != "" || strings.TrimSpace(d.Company.Website) != "" + hasPerson := strings.TrimSpace(d.Contact.FirstName+d.Contact.LastName+d.Contact.Email) != "" + if !hasCompany && !hasPerson && d.CompanyID == 0 { + fail("Give a company, a person, or both.") + return + } + if d.CompanyID == 0 && hasCompany { + if strings.TrimSpace(d.Company.Name) == "" { + fail("Give the company's name.") + return + } + id, _, err := prospects.AddCompany(s.DB, d.Company, now) + if err != nil { + fail(addError(err)) + return + } + d.CompanyID = id + } + if hasPerson { + d.Contact.CompanyID = d.CompanyID + if _, _, err := prospects.AddContact(s.DB, d.Contact, now); err != nil { + fail(addError(err)) + return + } + } else if d.CompanyID != 0 && !hasCompany { + fail("Give the person's name or email.") + return + } + redirect(w, r, "/prospects", "prospect-added") +} + +func addError(err error) string { + if errors.Is(err, prospects.ErrSuppressed) { + return "That's on your suppression list (" + strings.TrimSuffix(err.Error(), ": "+prospects.ErrSuppressed.Error()) + + "), so it can't be added. Take it off the list first if that's a mistake." + } + return err.Error() +} + +// --- Suppression list --- + +func (s *Server) suppressedPage(w http.ResponseWriter, r *http.Request) { + s.renderSuppressed(w, r, "", "") +} + +func (s *Server) renderSuppressed(w http.ResponseWriter, r *http.Request, value, errMsg string) { + list, err := prospects.Suppressions(s.DB) + if err != nil { + s.serverError(w, err) + return + } + s.render(w, r, "suppressed", page{Title: "Suppression list", Nav: "prospects/suppressed", Error: errMsg, Data: map[string]any{ + "List": list, + "Value": value, + }}) +} + +func (s *Server) suppressedAction(w http.ResponseWriter, r *http.Request) { + if err := r.ParseForm(); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + value := r.PostFormValue("value") + if r.PostFormValue("remove") != "" { + if err := prospects.Unsuppress(s.DB, r.PostFormValue("kind"), value); err != nil { + s.renderSuppressed(w, r, "", err.Error()) + return + } + redirect(w, r, "/prospects/suppressed", "unsuppressed") + return + } + if err := prospects.Suppress(s.DB, "", value, r.PostFormValue("reason"), time.Now()); err != nil { + s.renderSuppressed(w, r, value, err.Error()) + return + } + redirect(w, r, "/prospects/suppressed", "suppressed") +} diff --git a/internal/web/search.go b/internal/web/search.go index 6d503cd..2172416 100644 --- a/internal/web/search.go +++ b/internal/web/search.go @@ -8,8 +8,17 @@ import ( "supermarket/internal/content" "supermarket/internal/inventory" "supermarket/internal/profile" + "supermarket/internal/prospects" ) +// prospectBadge is a prospect's status as search shows it. +func prospectBadge(status string) string { + if status == prospects.StatusRejected { + return "set aside" + } + return status +} + // hit is one search result. type hit struct { Title, Detail, Link string @@ -143,6 +152,29 @@ func (s *Server) search(q string) ([]hitGroup, error) { posts = append(posts, hit{Title: text, Detail: detail, Link: link, Badge: d.Status}) } + companies, people, err := prospects.Search(s.DB, words, searchLimit) + if err != nil { + return nil, err + } + var prospectHits []hit + for _, c := range companies { + detail := "Company" + if c.Domain != "" { + detail += " · " + c.Domain + } + prospectHits = append(prospectHits, hit{Title: c.Name, Detail: detail, Link: "/prospects?status=" + c.Status, Badge: prospectBadge(c.Status)}) + } + for _, p := range people { + detail := "Person" + if p.Title != "" { + detail += " · " + p.Title + } + if p.Email != "" { + detail += " · " + p.Email + } + prospectHits = append(prospectHits, hit{Title: p.Name(), Detail: detail, Link: "/prospects?status=" + p.Status, Badge: prospectBadge(p.Status)}) + } + var settings []hit if p, err := profile.Load(s.DB); err == nil && p.IsSet() { for _, pr := range p.Products { @@ -158,7 +190,7 @@ func (s *Server) search(q string) ([]hitGroup, error) { } var groups []hitGroup - for _, g := range []hitGroup{{"Posts", posts}, {"Fetched items", found}, {"Inventory", inv}, {"Settings", settings}} { + for _, g := range []hitGroup{{"Posts", posts}, {"Fetched items", found}, {"Inventory", inv}, {"Prospects", prospectHits}, {"Settings", settings}} { if len(g.Hits) > 0 { groups = append(groups, g) } diff --git a/internal/web/server.go b/internal/web/server.go index 05e4ef3..a980d3c 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -127,6 +127,12 @@ func (s *Server) Handler() (http.Handler, error) { mux.HandleFunc("POST /drafts/{id}/{action}", s.draftAction) mux.HandleFunc("POST /reddit/rules/{name}", s.refreshRules) + mux.HandleFunc("GET /prospects", s.prospectsPage) + mux.HandleFunc("GET /prospects/new", s.prospectForm) + 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/{kind}/{id}/{action}", s.prospectAction) mux.HandleFunc("GET /crm", s.crmPage) mux.HandleFunc("GET /crm/reach", s.crmReach) mux.HandleFunc("POST /crm/{action}", s.crmAction) @@ -263,6 +269,8 @@ type page struct { Data any Inbox int // drafts waiting for review, shown in the menu Query string // the search box's text + + NewProspects int // companies and people waiting for review, shown in the menu } // Section is the top bar's first breadcrumb, from Nav. @@ -290,7 +298,7 @@ type module struct { var modules = []module{ {"content", "Content", "Phase 1", "Draft posts from partner and competitor news and your own products; review and publish to X, LinkedIn and Reddit.", "/content"}, - {"prospects", "Prospects", "Phase 2", "Find companies and people who fit your targets, and add the ones you approve to EspoCRM through Hermes.", "/crm"}, + {"prospects", "Prospects", "Phase 2", "Find companies and people who fit your targets, and add the ones you approve to EspoCRM through Hermes.", "/prospects"}, {"seo", "SEO", "Phase 3", "Audit your websites and open fixes as pull requests on your Hugo repositories.", ""}, {"metrics", "Metrics", "Phase 4", "Pipeline influence, CAC, CLV and NRR from Stripe, EspoCRM and Plausible.", ""}, {"sites", "Sites", "Phase 5", "Build pages and sites from a component library and publish them through Gitea.", ""}, @@ -309,6 +317,7 @@ func (s *Server) render(w http.ResponseWriter, r *http.Request, name string, p p } p.Version = s.Version p.Inbox = s.inboxCount() + p.NewProspects = s.newProspects() if p.Flash == "" { p.Flash = flashes[r.URL.Query().Get("msg")] } @@ -340,6 +349,12 @@ var flashes = map[string]string{ "reddit-connected": "Reddit is connected.", "crm-test": "Test Lead queued. Hermes creates it on its next run; or run it now (below).", "crm-sync": "Sync requested: Hermes copies CRM records on its next run.", + "accepted": "Accepted: queued for the CRM. Hermes adds it on its next run.", + "rejected": "Set aside.", + "reconsidered": "Back in New.", + "suppressed": "Added to the suppression list.", + "unsuppressed": "Taken off the suppression list.", + "prospect-added": "Added. Review it below.", "rules-refreshed": "Rules refreshed.", "imported": "Imported.", "oauth-expired": "That sign-in took too long or was already used. Try again.", @@ -355,7 +370,11 @@ var flashes = map[string]string{ func redirect(w http.ResponseWriter, r *http.Request, path, msg string) { if msg != "" { - path += "?msg=" + url.QueryEscape(msg) + sep := "?" + if strings.Contains(path, "?") { + sep = "&" + } + path += sep + "msg=" + url.QueryEscape(msg) } http.Redirect(w, r, path, http.StatusSeeOther) } diff --git a/internal/web/server_test.go b/internal/web/server_test.go index 3df1aa3..dda120e 100644 --- a/internal/web/server_test.go +++ b/internal/web/server_test.go @@ -25,6 +25,7 @@ import ( "supermarket/internal/mcpserver" "supermarket/internal/models" "supermarket/internal/profile" + "supermarket/internal/prospects" "supermarket/internal/secrets" ) @@ -97,7 +98,8 @@ func TestEveryPageRenders(t *testing.T) { "/inventory/new", "/inventory/1", "/inventory/import", "/inventory/export", "/settings/ai", "/settings/accounts", "/settings/core", "/static/app.css", "/favicon.ico", "/static/favicon.png", "/static/logo.png", "/static/apple-touch-icon.png", "/search", "/crm", "/search?q=rival", "/search?q=nothing+here", "/static/htmx.min.js", "/healthz", "/content", "/content/1", "/content/1?dismissed=1", "/posts", "/posts?msg=drafted", - "/content/scheduled", "/content/published"} { + "/content/scheduled", "/content/published", + "/prospects", "/prospects?status=accepted", "/prospects?status=rejected", "/prospects/new", "/prospects/suppressed"} { rec := do(h, http.MethodGet, path, nil, nil) if rec.Code != http.StatusOK { t.Errorf("core=%v GET %s: %d %s", c != nil, path, rec.Code, rec.Body.String()) @@ -538,3 +540,62 @@ func TestCRMReachHint(t *testing.T) { t.Errorf("unreachable: %s", body) } } + +// Prospects: add by hand, see the CRM warning, accept into the CRM queue, +// and the suppression list stops what's on it. +func TestProspectsReview(t *testing.T) { + s, h := newTestServer(t, nil) + rec, _ := crm.RecordFrom("Account", map[string]any{"id": "a1", "name": "Acme", "website": "https://acme.com"}, time.Now()) + crm.Ingest(s.DB, []crm.Record{rec}) + + if rec := postForm(h, "/prospects/new", url.Values{}); !strings.Contains(rec.Body.String(), "Give a company, a person, or both") { + t.Error("an empty form was accepted") + } + form := url.Values{"company_name": {"Acme"}, "website": {"acme.com"}, "why": {"Runs its own servers"}, + "first_name": {"Pat"}, "last_name": {"Lee"}, "title": {"CTO"}, "email": {"pat@acme.com"}, "source_detail": {"Met at FOSDEM"}} + if rec := postForm(h, "/prospects/new", form); rec.Code != http.StatusSeeOther { + t.Fatalf("add: %d %s", rec.Code, rec.Body.String()) + } + body := do(h, http.MethodGet, "/prospects", nil, nil).Body.String() + for _, want := range []string{"Acme", "Pat Lee", "Runs its own servers", "Met at FOSDEM", "Already in your CRM", "Accept with 1 person", + `2`} { + if !strings.Contains(body, want) { + t.Errorf("review page lacks %q in %s", want, body) + } + } + if rec := postForm(h, "/prospects/company/1/accept-all", url.Values{"tab": {"new"}}); rec.Code != http.StatusSeeOther { + t.Fatalf("accept all: %d %s", rec.Code, rec.Body.String()) + } + as, _ := crm.List(s.DB, 10) + if len(as) != 2 { + t.Fatalf("queued: %+v", as) + } + if body := do(h, http.MethodGet, "/prospects?status=accepted", nil, nil).Body.String(); !strings.Contains(body, "waiting for Hermes") { + t.Error("accepted tab doesn't show the CRM state") + } + + // Suppression. + postForm(h, "/prospects/new", url.Values{"first_name": {"Ray"}, "last_name": {"Doe"}, "email": {"ray@other.org"}}) + if rec := postForm(h, "/prospects/suppressed", url.Values{"value": {"other.org"}, "reason": {"partner"}}); rec.Code != http.StatusSeeOther { + t.Fatalf("suppress: %d %s", rec.Code, rec.Body.String()) + } + if body := do(h, http.MethodGet, "/prospects?status=rejected", nil, nil).Body.String(); !strings.Contains(body, "Ray Doe") { + t.Error("a suppressed prospect should be set aside") + } + if rec := postForm(h, "/prospects/new", url.Values{"last_name": {"Kim"}, "email": {"kim@other.org"}}); !strings.Contains(rec.Body.String(), "suppression list (kim@other.org)") { + t.Errorf("adding a suppressed person: %s", rec.Body.String()) + } + if body := do(h, http.MethodGet, "/prospects/suppressed", nil, nil).Body.String(); !strings.Contains(body, "other.org") || !strings.Contains(body, "partner") { + t.Error("suppression list page") + } + postForm(h, "/prospects/suppressed", url.Values{"kind": {"domain"}, "value": {"other.org"}, "remove": {"1"}}) + if list, _ := prospects.Suppressions(s.DB); len(list) != 0 { + t.Errorf("remove: %+v", list) + } + if body := do(h, http.MethodGet, "/search?q=pat+cto", nil, nil).Body.String(); !strings.Contains(body, "Pat Lee") || !strings.Contains(body, "/prospects?status=accepted") { + t.Error("search doesn't find the prospect") + } + if rec := postForm(h, "/prospects/contact/99/accept", url.Values{}); rec.Code != http.StatusNotFound { + t.Errorf("missing prospect: %d", rec.Code) + } +} diff --git a/internal/web/static/app.css b/internal/web/static/app.css index 384fb6a..422bd09 100644 --- a/internal/web/static/app.css +++ b/internal/web/static/app.css @@ -371,3 +371,12 @@ form.inline { display: inline-block; margin: 0 0 0.75rem; } .by-hand p { margin: 0 0 0.5rem; } .by-hand-done { margin: 0.5rem 0 0.75rem; } .by-hand-done .row input { margin: 0; } + +/* Prospects review */ +.prospect h2 { margin: 0 0 0.2rem; } +.prospect-head { display: flex; justify-content: space-between; align-items: flex-start; gap: 1rem; flex-wrap: wrap; } +.prospect-head .row-actions { display: flex; flex-wrap: wrap; gap: 0.35rem; align-items: center; justify-content: flex-end; white-space: normal; } +.prospect-head .row-actions form { margin: 0; } +.prospect .why { margin: 0.6rem 0 0.3rem; } +.prospect .people { margin: 0.9rem 0 0.5rem; } +.prospect .warnings { margin: 0.5rem 0; } diff --git a/internal/web/templates/layout.html b/internal/web/templates/layout.html index b14249c..07cb6bc 100644 --- a/internal/web/templates/layout.html +++ b/internal/web/templates/layout.html @@ -40,6 +40,8 @@ {{end}} {{if eq .ID "prospects"}} {{end}} diff --git a/internal/web/templates/prospect-new.html b/internal/web/templates/prospect-new.html new file mode 100644 index 0000000..742438a --- /dev/null +++ b/internal/web/templates/prospect-new.html @@ -0,0 +1,35 @@ +{{define "content"}}{{with .Data}} +

{{if .For}}Add a person at {{.For}}{{else}}Add a prospect{{end}}

+

{{if .For}}They go into review with {{.For}}.{{else}}A company, a person at it, or both. They go into review first; nothing reaches your CRM until you accept it.{{end}}

+ +
+ {{if .For}} + {{else}} +

Company

+
+ + + + + + +
+ +

Person (optional)

+ {{end}} +
+ + + + + + +
+ +
+ + Cancel +
+
+{{end}}{{end}} diff --git a/internal/web/templates/prospects.html b/internal/web/templates/prospects.html new file mode 100644 index 0000000..a4a242b --- /dev/null +++ b/internal/web/templates/prospects.html @@ -0,0 +1,121 @@ +{{define "content"}}{{with .Data}}{{$tab := .Tab}}{{$matches := .Matches}} +
+

Review prospects

+
+ Add a prospect +
+
+

Companies and people who may fit your targets. Nothing goes to your CRM until you accept it: accepting a company adds an Account, accepting a person adds a Lead, through the CRM queue. Each one keeps where and when it was found.

+ + + +{{if and (eq $tab "new") (or .Companies .Loose)}} +

{{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}}

+{{end}} + +{{range .Companies}}{{$c := .}} +
+
+
+

{{.Name}}{{if ne .Status $tab}} {{template "prospect-status" .Status}}{{end}}

+

+ {{with .Website}}{{$c.Domain}}{{end}} + {{with .Industry}} · {{.}}{{end}}{{with .Size}} · {{.}}{{end}}{{with .Location}} · {{.}}{{end}} + {{with .LinkedIn}} · LinkedIn{{end}} +

+
+ {{if eq .Status $tab}} +
+ {{if eq $tab "new"}} + {{if .Contacts}}
{{end}} +
+
+ {{if .Domain}}
{{end}} + {{else if eq $tab "accepted"}} + {{template "crm-state" dict "CRM" .CRM "Kind" "company" "ID" .ID "Tab" $tab}} + {{else}} +
+ {{end}} +
+ {{end}} +
+ {{with .Why}}

{{.}}

{{end}} +

{{template "provenance" .}}

+ {{with index $matches (printf "company:%d" .ID)}}{{template "crm-matches" .}}{{end}} + + {{if .Contacts}} + + {{end}} + {{if eq $tab "new"}}

Add a person at {{.Name}}

{{end}} +
+{{end}} + +{{if .Loose}} +
+

People without a company

+ +
+{{end}} + +{{if not (or .Companies .Loose)}} +
+ {{if eq $tab "new"}}

Nothing to review. Add a prospect by hand; finding them for you comes next.

+ {{else if eq $tab "accepted"}}

Nothing accepted yet.

+ {{else}}

Nothing set aside.

{{end}} +
+{{end}} +{{end}}{{end}} + +{{define "contact"}}{{$p := .P}}{{$tab := .Tab}} +
  • +
    +
    + {{$p.Name}}{{with $p.Title}} · {{.}}{{end}}{{if ne $p.Status $tab}} {{template "prospect-status" $p.Status}}{{end}} +
    + {{with $p.Email}}{{.}}{{if eq $p.EmailStatus "valid"}} verified{{else if eq $p.EmailStatus "risky"}} risky{{else if eq $p.EmailStatus "invalid"}} bounces{{else}} not verified{{end}}{{end}} + {{with $p.Phone}} · {{.}}{{end}} + {{with $p.LinkedIn}} · LinkedIn{{end}} +
    +
    {{template "provenance" $p}}
    + {{with index .Matches (printf "contact:%d" $p.ID)}}{{template "crm-matches" .}}{{end}} +
    + {{if eq $p.Status $tab}} +
    + {{if eq $tab "new"}} +
    +
    + {{if $p.Email}}
    {{end}} + {{else if eq $tab "accepted"}} + {{template "crm-state" dict "CRM" $p.CRM "Kind" "contact" "ID" $p.ID "Tab" $tab}} + {{else}} +
    + {{end}} +
    + {{end}} +
    +
  • +{{end}} + +{{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://")}}source{{else}}{{.}}{{end}}{{end}}{{end}} + +{{define "crm-matches"}} +

    Already in your CRM: {{range $i, $r := .}}{{if $i}}, {{end}}{{$r.Entity}} {{$r.Name}}{{with $r.Email}} ({{.}}){{end}}{{end}}.

    +{{end}} + +{{define "crm-state"}} +{{if eq .CRM.Status "done"}}{{if eq .CRM.Outcome "existing"}}already in the CRM{{else}}in the CRM{{end}} +{{else if eq .CRM.Status "failed"}}failed CRM queue +{{else if eq .CRM.Status "cancelled"}}cancelled +
    +{{else if eq .CRM.Status "claimed"}}with Hermes +{{else if .CRM.Status}}waiting for Hermes +{{else}}accepted{{end}} +{{end}} diff --git a/internal/web/templates/suppressed.html b/internal/web/templates/suppressed.html new file mode 100644 index 0000000..975c00f --- /dev/null +++ b/internal/web/templates/suppressed.html @@ -0,0 +1,35 @@ +{{define "content"}}{{with .Data}} +

    Suppression list

    +

    People and companies Supermarket must never add to your CRM: someone who asked not to be contacted, existing customers, partners, competitors. It's checked before a prospect is added, and again before anything is queued. A domain covers everyone with an email there.

    + +
    +
    + + +
    + +
    + +{{if .List}} + + + + {{range .List}} + + + + + + + {{end}} + +
    Email or domainReasonAdded
    {{.Value}} {{.Kind}}{{.Reason}}{{ago .CreatedAt}} +
    + + +
    +
    +{{else}} +

    The list is empty.

    +{{end}} +{{end}}{{end}}