diff --git a/.env.example b/.env.example index 583d02b4d..9c20d13a6 100644 --- a/.env.example +++ b/.env.example @@ -623,6 +623,21 @@ PUBSUB_ENABLED=false # SEARCH_API_URL= # SEARCH_API_KEY= +# === Lead finder (optional) =================================================== +# +# Works with nothing set: OpenStreetMap through public Overpass servers, the +# Photon geocoder and OpenFreeMap tiles. Your own Overpass (comma-separated, tried +# in order) is far more dependable than the shared public ones. Instance keys let +# every workspace without its own key search that source, at a credit a page. +# A map style hosted elsewhere also needs its origins in WARMBLY_CSP_CONNECT_ORIGINS. +# LEAD_FINDER_OVERPASS_URL= +# LEAD_FINDER_GEOCODER_URL= +# LEAD_FINDER_MAP_STYLE_URL= +# LEAD_FINDER_MAP_STYLE_DARK_URL= +# LEAD_FINDER_GOOGLE_PLACES_API_KEY= +# LEAD_FINDER_FOURSQUARE_API_KEY= +# LEAD_FINDER_OUTSCRAPER_API_KEY= + # === Integrations (optional) ================================================== # Shared redirect URI for the CRM and messaging OAuth flows. Unset, it becomes diff --git a/cmd/backend/main.go b/cmd/backend/main.go index 991ccf302..a00a73554 100644 --- a/cmd/backend/main.go +++ b/cmd/backend/main.go @@ -83,6 +83,7 @@ import ( "github.com/warmbly/warmbly/internal/app/instancesettings" "github.com/warmbly/warmbly/internal/app/integration" "github.com/warmbly/warmbly/internal/app/keystatus" + "github.com/warmbly/warmbly/internal/app/leadfinder" "github.com/warmbly/warmbly/internal/app/leadsync" "github.com/warmbly/warmbly/internal/app/mailboxavatar" "github.com/warmbly/warmbly/internal/app/mailboximport" @@ -388,6 +389,7 @@ func main() { var leadSyncServiceForHandler leadsync.Service var salesforceServiceForHandler *salesforce.Service var apolloServiceForHandler *apollo.Service + var leadFinderServiceForHandler *leadfinder.Service var clayServiceForHandler *clay.Service ctx, cancel := context.WithCancel(context.Background()) @@ -2313,6 +2315,29 @@ func main() { }) go contactImportService.Run(ctx) } + if contactService != nil { + // The lead finder's keyed providers read the workspace's own key first, + // then the operator's; OpenStreetMap needs none. + leadfinder.RegisterKeyChecks(integrationServiceForHandler) + leadFinderServiceForHandler = leadfinder.NewService(leadfinder.Deps{ + Repo: repository.NewLeadFinderRepository(primaryDB.Pool), + Integrations: integrationServiceForHandler, + Contacts: contactService, + Verifier: emailVerifyService, + Credits: creditService, + Audit: auditService, + Config: leadfinder.Config{ + OverpassURL: cfg.GetStringOptional(ctx, "LEAD_FINDER_OVERPASS_URL", "lead_finder/overpass_url", ""), + GeocoderURL: cfg.GetStringOptional(ctx, "LEAD_FINDER_GEOCODER_URL", "lead_finder/geocoder_url", ""), + MapStyleLight: cfg.GetStringOptional(ctx, "LEAD_FINDER_MAP_STYLE_URL", "lead_finder/map_style_url", ""), + MapStyleDark: cfg.GetStringOptional(ctx, "LEAD_FINDER_MAP_STYLE_DARK_URL", "lead_finder/map_style_dark_url", ""), + GoogleKey: cfg.GetSecretOptional(ctx, "LEAD_FINDER_GOOGLE_PLACES_API_KEY", "lead_finder/google_places_api_key", ""), + FoursquareKey: cfg.GetSecretOptional(ctx, "LEAD_FINDER_FOURSQUARE_API_KEY", "lead_finder/foursquare_api_key", ""), + OutscraperKey: cfg.GetSecretOptional(ctx, "LEAD_FINDER_OUTSCRAPER_API_KEY", "lead_finder/outscraper_api_key", ""), + }, + }) + go jobrun.Loop(ctx, "lead_enrichment_runs", time.Minute, true, leadFinderServiceForHandler.RunPendingEnrichment) + } // HubSpot as the workspace CRM: write-through for the CRM service, the // activity sink, and the outbox for automation-written records. The @@ -2679,6 +2704,7 @@ func main() { SalesforceService: salesforceServiceForHandler, ApolloService: apolloServiceForHandler, ClayService: clayServiceForHandler, + LeadFinderService: leadFinderServiceForHandler, WebsocketURI: websocketURI, diff --git a/deploy/config/env.example b/deploy/config/env.example index ae31ab75c..37a73ff06 100644 --- a/deploy/config/env.example +++ b/deploy/config/env.example @@ -343,6 +343,21 @@ CHECK_ORIGIN=false # SEARCH_API_URL= # SEARCH_API_KEY= +# === Lead finder (optional) =================================================== +# +# Works with nothing set: OpenStreetMap through public Overpass servers, the +# Photon geocoder and OpenFreeMap tiles. Your own Overpass (comma-separated, tried +# in order) is far more dependable than the shared public ones. Instance keys let +# every workspace without its own key search that source, at a credit a page. +# A map style hosted elsewhere also needs its origins in WARMBLY_CSP_CONNECT_ORIGINS. +# LEAD_FINDER_OVERPASS_URL= +# LEAD_FINDER_GEOCODER_URL= +# LEAD_FINDER_MAP_STYLE_URL= +# LEAD_FINDER_MAP_STYLE_DARK_URL= +# LEAD_FINDER_GOOGLE_PLACES_API_KEY= +# LEAD_FINDER_FOURSQUARE_API_KEY= +# LEAD_FINDER_OUTSCRAPER_API_KEY= + # === Observability === # Optional in EVERY environment, including APP_ENV=prod: with none of these set # an error is written to the service's own log and leaves the machine nowhere. diff --git a/docker-compose.yml b/docker-compose.yml index 85e2057cb..75cc0cdb4 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -229,6 +229,15 @@ x-selfhost-env: &selfhost-env SEARCH_API_URL: ${SEARCH_API_URL:-} SEARCH_API_KEY: ${SEARCH_API_KEY:-} + # Lead finder. All optional: OpenStreetMap, Photon and OpenFreeMap work keyless. + LEAD_FINDER_OVERPASS_URL: ${LEAD_FINDER_OVERPASS_URL:-} + LEAD_FINDER_GEOCODER_URL: ${LEAD_FINDER_GEOCODER_URL:-} + LEAD_FINDER_MAP_STYLE_URL: ${LEAD_FINDER_MAP_STYLE_URL:-} + LEAD_FINDER_MAP_STYLE_DARK_URL: ${LEAD_FINDER_MAP_STYLE_DARK_URL:-} + LEAD_FINDER_GOOGLE_PLACES_API_KEY: ${LEAD_FINDER_GOOGLE_PLACES_API_KEY:-} + LEAD_FINDER_FOURSQUARE_API_KEY: ${LEAD_FINDER_FOURSQUARE_API_KEY:-} + LEAD_FINDER_OUTSCRAPER_API_KEY: ${LEAD_FINDER_OUTSCRAPER_API_KEY:-} + # Slack app. The OAuth pair lets workspaces connect for notifications; the # signing secret turns on the assistant, the inbox and buttons. SLACK_OAUTH_CLIENT_ID: ${SLACK_OAUTH_CLIENT_ID:-} diff --git a/docs/content/docs/api/endpoints.mdx b/docs/content/docs/api/endpoints.mdx index 5f6134b3a..971c2ca72 100644 --- a/docs/content/docs/api/endpoints.mdx +++ b/docs/content/docs/api/endpoints.mdx @@ -175,6 +175,37 @@ The import pair is two steps over the same file: preview parses it and suggests AI contact research charges credits (2 per run, billable even when it finds nothing) and only saves cited findings. See the [AI contact research](/guides/ai-contact-research/) guide. The batch endpoint accepts up to 500 contact ids and drains in the background. +### Lead finder + +| Method | Path | API Permission | +|--------|------|----------------| +| GET | `/leads/config` | `READ_CONTACTS` | +| GET | `/leads/geocode` | `READ_CONTACTS` | +| POST | `/leads/search` | `WRITE_CONTACTS` | +| POST | `/leads/query` | `READ_CONTACTS` | +| POST | `/leads/points` | `READ_CONTACTS` | +| POST | `/leads/facets` | `READ_CONTACTS` | +| POST | `/leads/export` | `READ_CONTACTS` | +| PATCH | `/leads` | `BULK_CONTACTS` | +| DELETE | `/leads` | `BULK_CONTACTS` | +| POST | `/leads/enrich` | `BULK_CONTACTS` | +| GET | `/leads/enrichments` | `READ_CONTACTS` | +| GET | `/leads/enrichments/:id` | `READ_CONTACTS` | +| POST | `/leads/contacts` | `BULK_CONTACTS` | +| GET | `/leads/searches` | `READ_CONTACTS` | +| PATCH | `/leads/searches/:id` | `WRITE_CONTACTS` | +| DELETE | `/leads/searches/:id` | `WRITE_CONTACTS` | +| GET | `/leads/:id` | `READ_CONTACTS` | +| PATCH | `/leads/:id` | `WRITE_CONTACTS` | +| POST | `/leads/:id/people` | `WRITE_CONTACTS` | +| PATCH | `/leads/:id/people/:personId` | `WRITE_CONTACTS` | +| DELETE | `/leads/:id/people/:personId` | `WRITE_CONTACTS` | +| POST | `/leads/:id/people/:personId/find-email` | `WRITE_CONTACTS` | + +Leads are prospect contacts, so the [lead finder](/guides/lead-finder/) uses the contact scopes and the **View contacts** and **Manage contacts** member permissions. `POST /leads/search` runs one page of a source search over an `area` (`bbox`, `circle` or `polygon`) and stores what it finds; send `search_id` alone to fetch the next page of the same search. `POST /leads/query`, `/leads/points` and `/leads/facets` are reads with a `filter` body; `query` pages with an opaque `cursor` and a `limit` from 1 to 200 and answers `data` plus `pagination` with a `total`. Bulk calls take a selection: `lead_ids` (at most 5,000), or `all: true` with a `filter`. + +`POST /leads/enrich` starts a background run that reads each lead's website for emails, socials and (unless `people` is `false`) the people it names, then works out and checks their addresses, and answers `202` with the run; follow it at `/leads/enrichments/:id`. It costs one credit per website read, refunded when the site never answers. `GET /leads/:id` carries the lead's `people`. `POST /leads/:id/people` adds a person by `name` or `first_name` and `last_name`, and without an `email` works out their address at the lead's domain on the spot for one credit, refunded when none turns up; `find-email` does the same for someone already listed. People are matched by name, so adding someone again lands on the same person. `POST /leads/contacts` takes `who` (`business`, `people` or `both`), `include_guessed`, `segment_ids`, `category_ids`, `campaign_ids`, `skip_active_in_other_campaigns` and `keep_existing` (leave contacts you already have as they are); `POST /leads/export` takes `rows` (`leads` or `people`). A search through a source the instance pays for costs one credit a page. `POST /leads/search` and `/leads/enrich` honor `Idempotency-Key`. A paid address lookup, `find-email` or adding a person without an `email`, charges again when retried, so retry it only after reading the person back. The other writes set values or update existing contacts, so a retry lands on the same state. `POST /leads/export` answers the file itself (`format` is `csv`, `xlsx` or `json`). + ### Segments | Method | Path | API Permission | diff --git a/docs/content/docs/api/error-codes.mdx b/docs/content/docs/api/error-codes.mdx index 51dafe25e..98c1d2197 100644 --- a/docs/content/docs/api/error-codes.mdx +++ b/docs/content/docs/api/error-codes.mdx @@ -603,6 +603,25 @@ The [Apollo](/guides/apollo/) and [Clay](/guides/clay/) endpoints answer with th | `apollo_key_missing` | 422 | The Apollo connection has no API key | | `apollo_rate_limited` | 429 | Apollo's rate limit for the account was reached. Retry later | +#### Lead finder refusals + +The [lead finder](/guides/lead-finder/) endpoints answer with their own codes. + +| `code` | Status | Meaning | +|--------|--------|---------| +| `lead_search_empty` | 400 | `POST /leads/search` named neither a `query` nor a `category` | +| `lead_search_area` | 400 | The search `area` is not a usable rectangle, circle (50 m to 50 km) or shape (3 to 200 points), or it is larger than the source searches at once | +| `lead_search_exhausted` | 400 | `POST /leads/search` asked for the next page of a search that has no more results | +| `lead_provider_not_connected` | 400 | The chosen source needs an API key and neither the workspace nor the instance has one. Connect it under Integrations | +| `lead_provider_key` | 400 | The source refused the API key. Replace the key on its integration | +| `lead_selection_too_large` | 400 | A bulk call named more than 5,000 `lead_ids` | +| `lead_person_no_domain` | 400 | A person was added or searched for without an `email` on a lead with no website, so there is no domain to work an address out at | +| `lead_person_exists` | 409 | Renaming a person would give them the name of someone already on the lead | +| `lead_provider_quota` | 429 | The source is rate limiting the key or its quota is used up. Retry later | +| `lead_provider_unavailable` | 503 | The source did not answer, took too long, or (OpenStreetMap) every server is busy. Retry, or search a smaller area | + +A search through a source the instance pays for answers `402` with `insufficient_credits` past the credit balance and `429` with `usage_cap_exceeded` past a spend limit, and charges nothing. An enrichment run charges as it reads each website; one that reaches either limit stops with `status: "error"` and the reason in `last_error`, and leaves the remaining leads untouched. + #### Automation refusals | `code` | Status | Meaning | diff --git a/docs/content/docs/development/configuration.mdx b/docs/content/docs/development/configuration.mdx index e5b08daed..76e96024a 100644 --- a/docs/content/docs/development/configuration.mdx +++ b/docs/content/docs/development/configuration.mdx @@ -884,6 +884,25 @@ Set these on the backend and the consumer. Automatic inbox tagging is read by the backend, consumer, and `warmblyctl`. Both inbox-tagging variables are required; a key by itself does not start classification. See [Automatic inbox tagging](/guides/inbox-tagging/). +## Lead finder + +The [lead finder](/guides/lead-finder/) works with nothing set: OpenStreetMap through public Overpass servers, Komoot's public Photon geocoder for typed locations, and OpenFreeMap's keyless vector tiles for the map. Every variable here is optional and read by the backend. + +| Variable | What it does | Default | +|---|---|---| +| `LEAD_FINDER_OVERPASS_URL` | Overpass endpoints for OpenStreetMap searches, separated by commas and tried in order when one is busy. Point it at your own Overpass for dependable searches; the public ones are shared and often at capacity | `overpass-api.de`, `overpass.private.coffee` and `maps.mail.ru` mirrors | +| `LEAD_FINDER_GEOCODER_URL` | A Photon-compatible `/api` endpoint for the **Where** box | `https://photon.komoot.io/api` | +| `LEAD_FINDER_MAP_STYLE_URL`, `LEAD_FINDER_MAP_STYLE_DARK_URL` | MapLibre style JSON for the map in light and dark themes. The **Streets** style is offered only with the default styles | OpenFreeMap `positron` and `dark` | +| `LEAD_FINDER_GOOGLE_PLACES_API_KEY` | An instance-wide Google Maps Platform key with Places API (New). Every workspace without its own Google Places connection can then search Google, at one credit a page | unset | +| `LEAD_FINDER_FOURSQUARE_API_KEY` | An instance-wide Foursquare service key, used the same way | unset | +| `LEAD_FINDER_OUTSCRAPER_API_KEY` | An instance-wide Outscraper key, used the same way | unset | + +A workspace's own key, connected under Integrations, always takes precedence over the instance's and costs no credits. + +The dashboard's content security policy allows `https://tiles.openfreemap.org`. A map style served from anywhere else, including your own tile server, also needs its origin (and the origins of its tiles, sprites and glyphs) in `WARMBLY_CSP_CONNECT_ORIGINS` on the web container, or the map stays blank. + +Reading websites for emails runs from the backend, opens only public addresses on ports 80 and 443, and identifies itself as `WarmblyBot/1.0`. See [data control](/development/data-control/#outbound-calls) for every call the lead finder makes. + ## Tasks and billing Warmup replies use the same persisted SQL task identity with either queue provider. They wait at least 45 minutes after the exact parent receipt and recheck mailbox windows, roles, consent, standing, suppression and remaining budgets before native dispatch. Queue callbacks do not grant sending authority. See [diagnostic generation and rollout](/development/warmup-generation/). diff --git a/docs/content/docs/development/data-control.mdx b/docs/content/docs/development/data-control.mdx index 216efed47..ca74b03f3 100644 --- a/docs/content/docs/development/data-control.mdx +++ b/docs/content/docs/development/data-control.mdx @@ -350,6 +350,11 @@ These are made only when a workspace uses the feature behind them, so an instanc | DNS lookups | A workspace sets up a root redirect or a domain-wide tracking host, or proves a Google Workspace domain by DNS: `TXT`, address and `CNAME` lookups for that domain, through the host's resolver. Pending redirects are re-checked every 10 minutes, verified ones every 6 hours. A redirect or form redirect to a website the workspace does not send from also reads the website's `_warmbly` `TXT` record, on save and on each check; a [confirmed website](/guides/sending-domains/#confirm-your-website) is kept in `website_domains` while the record stays published, read again every 6 hours, and deleted once the record is definitively gone or with the workspace. The sending-domain authentication check (about once a day per domain, and on demand) reads SPF, DKIM and DMARC the same way, and when the host's resolver does not return a record it asks that domain's own nameservers directly on port 53 (never one on a private or loopback address) | | The redirect's own domain | Once a root redirect's DNS verifies, the backend opens `http:///` and `https:///` like a visitor, without following it off the domain, to see whether the redirect answers. Only public addresses on ports 80 and 443 are opened. Repeated with the DNS check: every 10 minutes while visitors do not get the redirect (for two weeks after it verified), every 6 hours otherwise | | Warmbly Cloud (`api.warmbly.com`, or `WARMBLY_CLOUD_URL`) | A linked instance has a root redirect [served from Warmbly Cloud](/guides/sending-domains/#serve-it-from-warmbly-cloud): the domain, the website and the `www` setting, with the instance's link token, when it is saved, moved, checked or removed, and whenever the instance re-reads Cloud's verdict (on the same schedule as its own redirects) | +| Lead finder map (`tiles.openfreemap.org`, or `LEAD_FINDER_MAP_STYLE_URL`) | While someone has the [lead finder](/guides/lead-finder/) open, their browser (not the server) loads the map's tiles, sprites and fonts. No lead or workspace data is sent | +| Lead finder sources (Overpass servers or `LEAD_FINDER_OVERPASS_URL`; `places.googleapis.com`, `places-api.foursquare.com`, `api.app.outscraper.com`) | A workspace searches the lead finder: the area's bounding box, the category and the typed words go to the chosen source, with the key of the workspace or the instance | +| Location search (`photon.komoot.io`, or `LEAD_FINDER_GEOCODER_URL`) | Someone types in the lead finder's **Where** box: the typed text and the map's center, a few times while they type | +| Business websites | Someone runs **Find people and emails**: the backend reads the selected businesses' own home pages, their `robots.txt` and up to six contact, team, about or legal pages each, as `WarmblyBot/1.0`. For a business listed without a website it first looks up a few domains built from the business's name and reads up to three of their home pages. Only public addresses on ports 80 and 443 are opened. Unless the request turns verification off (it is on by default), up to three addresses per lead are then checked like a contact's; any beyond the third are not checked | +| Business mail servers | The lead finder works out a person's address: each candidate is checked with the business domain's mail server the same way a contact's address is, a few per person and at most fifteen per business in a run, and nothing is sent | Everything else is you: mail through the mailboxes you connect, DNS lookups for the domains you check, and whatever integrations you configure. There is no telemetry, no phone-home, and no license check. diff --git a/docs/content/docs/guides/ai-credits.mdx b/docs/content/docs/guides/ai-credits.mdx index 1e1562314..93e4f1ccd 100644 --- a/docs/content/docs/guides/ai-credits.mdx +++ b/docs/content/docs/guides/ai-credits.mdx @@ -83,6 +83,9 @@ Each action reserves a flat **minimum** up front (which also gates an empty bala | Per-recipient AI variable, instant / research mode | 1 / 2 per recipient | | Web search by an AI step (only when results are found) | 1 | | Inbox agent handled thread | 5 | +| [Lead finder](/guides/lead-finder/) website read, including the people it names and their addresses (flat; refunded when the site never answers) | 1 per website | +| [Lead finder](/guides/lead-finder/) finding one person's email on request (flat; refunded when no address turns up) | 1 per person | +| [Lead finder](/guides/lead-finder/) search through a source the instance pays for (flat; free with your own key or OpenStreetMap) | 1 per page | Five rules govern the settle: diff --git a/docs/content/docs/guides/lead-finder.mdx b/docs/content/docs/guides/lead-finder.mdx new file mode 100644 index 000000000..d0f801331 --- /dev/null +++ b/docs/content/docs/guides/lead-finder.mdx @@ -0,0 +1,159 @@ +--- +title: Lead finder +description: "Find local businesses on a map, read their websites for the people who run them, emails and socials, filter and score them, then export them or add them to contacts and campaigns." +--- + +The lead finder searches a map for businesses of a kind, in the exact area you choose, and keeps every one it finds as a lead in your workspace. From there you can read each business's own website for the people who work there, email addresses and social profiles, work out and check those people's addresses, sort and filter the results, and turn the good ones into contacts or a campaign's leads. Open it from **Lead finder** in the sidebar. + +## Search an area + + + + + +Pick a category, type what you are looking for (for example `vegan bakery` or a business name), or both. + + + + + +Type a city, neighborhood or address under **Where** to move the map there. + + + + + +Search the visible map, or draw the exact area first with the rectangle, circle or shape tool on the left of the map. Draw a rectangle or circle by dragging across the map. Draw a shape by clicking its corners, then double-click (or press Enter) to finish. Escape cancels a drawing. + + + + + +Press **Search this area**. Pins appear on the map and the businesses fill the list below it. + + + + + +Only businesses inside the area you searched are kept. When a source has more results than one page, **Load more** fetches the next page of the same search. + +## Sources + +Where businesses come from is picked under **Source**, and the finder remembers your pick in this browser until that source is no longer connected. Every source returns the business's name, address, category and position; what else it returns differs. + +| Source | What it adds | Cost | +|---|---|---| +| OpenStreetMap | Websites, phone numbers, emails and opening hours where the map's contributors added them. Coverage is best in Europe and large cities | Free, no key | +| Google Places | Ratings, review counts, price level, hours, phone numbers, websites and whether a business has closed. Up to 60 results a search | Your Google Maps Platform key, billed by Google | +| Foursquare | Categories, chains, socials, ratings and hours, paged 50 at a time | Your Foursquare key, billed by Foursquare | +| Outscraper | Google Maps listings, plus emails and social profiles Outscraper finds from each business's domain | Your Outscraper key, billed by Outscraper | + +Connect a key under **Integrations**, in the Data group. The key is checked with one small search before it is saved, encrypted with your workspace's key and never shown again. A Warmbly instance can also provide a source with its own key; searching through it then costs one [credit](/guides/ai-credits/) a page. Your own key always takes precedence over the instance's. + +OpenStreetMap searches up to 2,500 km² at a time and is served by shared public servers that are sometimes busy. When one is, the finder tries the next and tells you if all of them are. + +Each source has its own terms about storing and reusing its data. Google's, for example, limit how long Places content may be kept. Check the terms of the source you use before exporting from it. + +## The map + +The controls on the right of the map change how leads are drawn: + +- **Pins or heatmap.** Pins cluster when they crowd and split as you zoom in. The heatmap shows where leads are densest, weighted by score. +- **Color pins by** reachability (email, website, phone only, nothing), status, score or rating. The legend in the corner says what each color means. +- **Map style** follows the dashboard's light or dark theme, or can be set to light, dark or streets. +- **Tilt** gives the map a 3D angle, and **Fit** frames every lead on the map. + +Hovering a pin shows its name, rating and how it can be reached. Clicking one opens its details. Shift-click a pin to add it to the selection, or use the lasso tool to select every lead inside a shape you drag. + +## Find people and emails + +**Find people and emails** reads each selected business's own website the way a visitor would: the home page and up to six of its contact, team, about and legal pages, nothing its `robots.txt` asks crawlers to skip. It collects: + +- the people the site names, with their titles (see [people](#people)) + +- email addresses, including ones written as `name [at] domain [dot] com` and ones hidden by Cloudflare's email protection +- links to Facebook, Instagram, LinkedIn, X, TikTok, YouTube, Pinterest and Yelp profiles +- phone numbers, when the source had none +- what the site is built with, and signals worth knowing before you reach out: no HTTPS, not mobile friendly, no analytics, an outdated copyright year, online booking, live chat or an online store + +When a listing has no website, the finder first looks for one from the business's name: a few likely domains (the name run together or hyphenated, with the town added, on the country's own ending and `.com`). A domain counts only when its home page shows the business's phone number, or its full name together with its town, street or postcode, so a parked domain or a namesake elsewhere is never taken. Many small businesses use a domain that cannot be guessed from their name, so this finds some of the missing websites, not all of them. A website found this way is marked with a sparkle in the list and costs the same as any other read; looking costs nothing. + +Up to three addresses per lead are then checked with the same verification your contacts get. The best one becomes the lead's primary email: a valid address on the business's own domain first, a front desk address such as `info@` before a named person's, and `noreply` addresses last. An invalid or suppressed address is never picked, but a `noreply` one can be when the lead has nothing better. + +Reading a website costs one [credit](/guides/ai-credits/). A site that never answers is refunded, and a lead with no website, even after looking for one, costs nothing. A self-hosted instance without billing charges no credits for the lead finder at all. Runs keep going in the background when you leave the page. Progress shows in a strip above the list, each business being read is marked in its row, and rows update as they are read. A run stops early, leaving the rest untouched, when the workspace runs out of credits. + +## People + +Reading a website also finds the people who work there, from: + +- team, staff, leadership and "meet the doctors" pages, where a name sits next to a role +- the legal notice (Impressum) that German, Austrian, Swiss and several other sites must carry, naming the owner or managing director +- structured data the site publishes for search engines (schema.org `Person`) +- a mailto link whose text is a name, a personal address such as `jane.doe@` on the business's own domain, and LinkedIn profiles linked from the site + +Each person is placed as an owner, executive, manager or staff member from their title, and the most senior are listed and worked on first. A lead's **People** tab lists them; the list shows how many each lead has, and **Has people** filters to leads with someone found. + +Then each person gets an address at the business's domain: + +1. An address the site published for them is kept and checked. +2. Otherwise their address is worked out from their name. When the site published any personal address, the domain's pattern (`first.last`, `jane@`, `jdoe@` and so on) is learned from it and tried first; otherwise the most common shapes are tried in turn. +3. Each candidate is checked with the domain's mail server, without sending anything. The first one it confirms is kept, and the pattern is remembered for everyone else at that business. + +The result says how far to trust it: + +| Shown as | Meaning | +|---|---| +| Confirmed | Published on the site, or worked out and confirmed by their mail server | +| Likely | Follows the address pattern this business uses, but the server would not confirm it | +| Best guess | The most common shape; nothing could confirm it | +| Not deliverable | The server refused it | +| Suppressed | On your [suppression list](/guides/unsubscribe/), so it is never mailed | + +Some mail servers accept any address (catch-all) and some hosted providers answer every check the same way, so neither can confirm a worked-out address. The **People** tab says so when that is the case, and the finder stops checking that domain rather than spending more checks on it. Checking needs outbound port 25, so on an instance that cannot reach it, worked-out addresses stay unconfirmed. + +**Find someone's email** at the bottom of the **People** tab takes a first and last name (and a title, if you like) and works out that person's address the same way, right away. It costs one [credit](/guides/ai-credits/), refunded when no address turns up. You can also add someone whose address you know, edit anyone, ask the finder to look again, or remove them; a contact made from them stays. Nothing your team typed in is overwritten by a later website read. + +## Score + +Every lead has a score from 0 to 100 that rates how reachable it is: a website (15), an email (25), an email that checked as valid (15), a phone number (15), social profiles (10), its rating (up to 10) and its review count (up to 10). Sort by **Best leads first** to work the reachable ones first. + +## Filter and organize + +The filter bar above the map and the list narrows what both show. Type to filter by name, email or domain, tap **Has email**, **Has website**, **Has phone** or **4+** stars, or open **Filters** for the rest: reachability (has email, website, phone or socials, or no website at all), rating, review count, score, status, category and tag. You can also hide leads already in your contacts, chains and franchises, and dismissed leads, or keep only what is in the current map view. + +Each lead has a status (new, saved, contacted or dismissed), tags and notes, set in its details or for a whole selection at once from the bar at the bottom of the screen. Your team sees the same leads, statuses and notes. + +The header shows which search the list is scoped to. Clear it to see every lead your workspace has found. + +## Saved searches + +Every search is listed under the search form, the latest few first with the rest a click away. Bookmark one to keep it under **Saved** at the top, rename it, or open it to see its leads and area again. Deleting a search keeps its leads. + +## Add to contacts + +**Add to contacts** turns the selected leads into contacts, and can add them to segments, labels and campaigns at the same time. A new segment can be made on the spot, named after the search by default. When you add them to a campaign, contacts another campaign is already emailing are added but not enrolled, unless you untick that. Choose who becomes a contact: + +- **The people**: everyone found at each business with an address. Each contact gets their first and last name, the business as the company, their phone (or the business's) and the verification result, plus `job_title`, `seniority`, `linkedin_url`, `company_linkedin_url`, `website`, `business_category`, `address`, `city`, `state`, `country`, `map_url` and `lead_score` as custom fields. Addresses that were worked out but not confirmed are left out unless you turn on **Include unconfirmed guesses** +- **The business**: each lead's own primary address, as described below +- **Both**: the people first, then each business's address, so an owner whose address is also the business's is added once, as a person + +For the business, each contact gets: + +- the lead's primary email, the business name as the company, and its phone number +- the verification result, when the address was checked +- `website`, `business_category`, `address`, `city`, `state`, `postcode`, `country`, `rating`, `review_count`, `map_url`, `facebook_url`, `instagram_url`, `linkedin_url`, `website_platform` and `lead_score` as [custom fields](/guides/contacts-crm/), ready for [variables](/guides/ai-variables/) in your emails + +A lead without an email is left out, as is a suppressed address. **Only verified addresses** also leaves out every lead whose address did not check as valid. A contact who already exists is never duplicated: by default the lead fills in its empty details and nothing it has is erased, and **Leave as is** keeps it exactly as it was. Either way it gets the segments, labels and campaigns you picked. Leads that became contacts show a check in the list. + +## Export + +**Export** downloads the selected leads, or every lead matching the filter, as CSV, Excel or JSON. Pick the columns: every field on this page is available, including every address found other than invalid or suppressed ones, the people found with their addresses unless suppressed, socials, the website's platform and signals, the score, status, tags and notes. + +Choose **One row per person** to get a row for each person found instead, starting with their name, first and last name, title, seniority, address, its status and confidence, LinkedIn, phone and the page they were found on, followed by the business columns you picked. Businesses with nobody found are left out of that file. + +## Good to know + +- One action takes at most 5,000 leads. +- A business found twice, by two searches or two people, is one lead. A new search refreshes what the source says about it and never blanks a field it already had. +- Leads and the people found at them move with the Contacts group of a [workspace export](/guides/workspace-export-import/). +- Reading the leads needs **View contacts**; searching, editing and adding them needs **Manage contacts**. API keys use the contact scopes; see the [scope map](/api/endpoints/). diff --git a/docs/content/docs/guides/meta.json b/docs/content/docs/guides/meta.json index 87fabdb5b..1d5eacdf6 100644 --- a/docs/content/docs/guides/meta.json +++ b/docs/content/docs/guides/meta.json @@ -20,6 +20,7 @@ "advisor", "---Contacts and inbox---", "contacts-crm", + "lead-finder", "segments", "forms", "website-tracking", diff --git a/docs/content/docs/guides/workspace-export-import.mdx b/docs/content/docs/guides/workspace-export-import.mdx index 784a5736c..3a3239ad4 100644 --- a/docs/content/docs/guides/workspace-export-import.mdx +++ b/docs/content/docs/guides/workspace-export-import.mdx @@ -79,7 +79,7 @@ The data is split into groups. Every export includes **Workspace**; the rest are | Group | Contents | |-------|----------| | Workspace | The organization, members with their [access scope](/guides/team-roles/#access-scope) and mailbox grants, roles, teams, mailboxes and their profile photos, mailbox tags, the column mappings saved by [mailbox imports](/guides/mailbox-import/), inbox vendor connections, [root redirects](/guides/sending-domains/#root-redirects), API keys, webhooks, and settings, including the website tracking site key. Always included | -| Contacts | Contacts, labels, the column mappings saved by [contact imports](/guides/contacts-crm/#importing), segments with their manual overrides, forms with their images, submissions, personalized link tickets and funnel events, notes, activities, the suppression list, and each contact's [HubSpot](/guides/hubspot/) record id, owner, lifecycle stage, lead status and company | +| Contacts | Contacts, labels, the column mappings saved by [contact imports](/guides/contacts-crm/#importing), [lead finder](/guides/lead-finder/) leads, the people found at them, and searches (a search reopens from its first page), segments with their manual overrides, forms with their images, submissions, personalized link tickets and funnel events, notes, activities, the suppression list, and each contact's [HubSpot](/guides/hubspot/) record id, owner, lifecycle stage, lead status and company | | Campaigns | Campaigns, folders, restricted members' campaign and folder grants, sequences, senders, linked segments, attachments, the email image library, per-campaign settings, each lead's step progress with its per-link clicks and per-event opens, the colleagues [copied on each lead](/guides/campaigns/#copying-colleagues-on-one-lead), [placement monitors](/guides/placement-tests/#campaign-placement-monitors), and the [unsubscribe links](/guides/unsubscribe/) already in recipients' inboxes | | CRM | Pipelines, deals, tasks, and meeting bookings | | Automations | Automations, connected integrations (including [Clay](/guides/clay/) defaults and events), saved [Apollo](/guides/apollo/) imports, lead sync sources, and the workspace's CRM mode: whether it runs on [HubSpot](/guides/hubspot/), its setup choices, the owner matches, and which Warmbly record is which HubSpot record | diff --git a/internal/api/handler/handler.go b/internal/api/handler/handler.go index 1a14346f9..aed5ddd6f 100644 --- a/internal/api/handler/handler.go +++ b/internal/api/handler/handler.go @@ -45,6 +45,7 @@ import ( "github.com/warmbly/warmbly/internal/app/instancesettings" "github.com/warmbly/warmbly/internal/app/integration" "github.com/warmbly/warmbly/internal/app/keystatus" + "github.com/warmbly/warmbly/internal/app/leadfinder" "github.com/warmbly/warmbly/internal/app/leadsync" "github.com/warmbly/warmbly/internal/app/mailboximport" "github.com/warmbly/warmbly/internal/app/mailpush" @@ -348,6 +349,8 @@ type Handler struct { ApolloService *apollo.Service // ClayService takes rows from Clay tables and sends events back to them. ClayService *clay.Service + // LeadFinderService finds businesses on a map and turns them into contacts. + LeadFinderService *leadfinder.Service // Public websocket URL used by frontend clients WebsocketURI string diff --git a/internal/api/handler/lead_finder.go b/internal/api/handler/lead_finder.go new file mode 100644 index 000000000..68b49d277 --- /dev/null +++ b/internal/api/handler/lead_finder.go @@ -0,0 +1,608 @@ +package handler + +import ( + "bytes" + "errors" + "fmt" + "net/http" + "strconv" + "strings" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" + "github.com/rs/zerolog/log" + + "github.com/warmbly/warmbly/internal/api/middleware" + "github.com/warmbly/warmbly/internal/app/leadfinder" + "github.com/warmbly/warmbly/internal/errx" + "github.com/warmbly/warmbly/internal/models" + "github.com/warmbly/warmbly/internal/utils/paging" +) + +// leadsReady resolves the organization and actor, or answers the request itself. +func (h *Handler) leadsReady(c *gin.Context) (uuid.UUID, uuid.UUID, bool) { + if h.LeadFinderService == nil { + errx.JSON(c, errx.New(errx.ServiceUnavailable, "The lead finder is not available on this instance")) + return uuid.Nil, uuid.Nil, false + } + orgID, ok := requireOrgID(c) + if !ok { + return uuid.Nil, uuid.Nil, false + } + userID, _ := middleware.GetUserUUID(c) + return orgID, userID, true +} + +// leadsFail answers a lead finder error: the service's own refusals as they +// are, anything else as an internal error with the cause logged. +func leadsFail(c *gin.Context, err error, what string) { + var xe *errx.Error + if errors.As(err, &xe) { + errx.JSON(c, xe) + return + } + log.Error().Err(err).Str("op", what).Msg("lead finder request failed") + errx.JSON(c, errx.InternalError()) +} + +func leadsParamID(c *gin.Context, name string) (uuid.UUID, bool) { + id, err := uuid.Parse(c.Param(name)) + if err != nil { + errx.JSON(c, errx.New(errx.BadRequest, "invalid id")) + return uuid.Nil, false + } + return id, true +} + +// LeadFinderConfig lists the providers, categories and map style. +func (h *Handler) LeadFinderConfig(c *gin.Context) { + orgID, _, ok := h.leadsReady(c) + if !ok { + return + } + c.JSON(http.StatusOK, h.LeadFinderService.FinderConfig(c.Request.Context(), orgID)) +} + +// LeadFinderGeocode looks up a typed location for the map. +func (h *Handler) LeadFinderGeocode(c *gin.Context) { + if _, _, ok := h.leadsReady(c); !ok { + return + } + var near *models.LatLng + lat, lng := c.Query("lat"), c.Query("lng") + if (lat == "") != (lng == "") { + errx.JSON(c, errx.New(errx.BadRequest, "lat and lng must be sent together")) + return + } + if lat != "" { + la, err1 := strconv.ParseFloat(lat, 64) + lo, err2 := strconv.ParseFloat(lng, 64) + if err1 != nil || err2 != nil || la < -90 || la > 90 || lo < -180 || lo > 180 { + errx.JSON(c, errx.New(errx.BadRequest, "lat and lng must be a point on the map")) + return + } + near = &models.LatLng{Lat: la, Lng: lo} + } + out, err := h.LeadFinderService.Geocode(c.Request.Context(), c.Query("q"), near, c.Query("lang")) + if err != nil { + leadsFail(c, err, "geocode") + return + } + c.JSON(http.StatusOK, gin.H{"data": out}) +} + +// SearchLeads runs one page of a provider search. A retry with the same +// Idempotency-Key replays the stored answer instead of searching again. +func (h *Handler) SearchLeads(c *gin.Context) { + orgID, userID, ok := h.leadsReady(c) + if !ok { + return + } + var req leadfinder.SearchRequest + if err := c.ShouldBindJSON(&req); err != nil { + errx.JSON(c, errx.InvalidBody(err)) + return + } + out, err := h.LeadFinderService.Search(c.Request.Context(), orgID, userID, req) + if err != nil { + leadsFail(c, err, "search") + return + } + if req.SearchID == nil { + h.auditOrg(c, models.AuditActionCreate, models.AuditEntityLeadSearch, &out.Search.ID, nil, + map[string]string{"provider": string(out.Search.Provider), "found": strconv.Itoa(out.Found)}) + } else { + h.auditOrg(c, models.AuditActionUpdate, models.AuditEntityLeadSearch, &out.Search.ID, nil, + map[string]string{"page": strconv.Itoa(out.Search.PagesFetched), "found": strconv.Itoa(out.Found)}) + } + c.JSON(http.StatusOK, out) +} + +type leadQuery struct { + Filter *models.LeadFilter `json:"filter"` + Sort models.LeadSort `json:"sort"` + Limit *int `json:"limit"` + Cursor string `json:"cursor"` +} + +// QueryLeads lists leads with a filter, a page at a time. A read with a body. +func (h *Handler) QueryLeads(c *gin.Context) { + orgID, _, ok := h.leadsReady(c) + if !ok { + return + } + var q leadQuery + if err := c.ShouldBindJSON(&q); err != nil { + errx.JSON(c, errx.InvalidBody(err)) + return + } + limit := 50 + if q.Limit != nil { + if *q.Limit < 1 || *q.Limit > 200 { + errx.JSON(c, errx.New(errx.BadRequest, "limit must be between 1 and 200")) + return + } + limit = *q.Limit + } + if q.Sort == "" { + q.Sort = models.LeadSortRecent + } + if !q.Sort.Valid() { + errx.JSON(c, errx.New(errx.BadRequest, "sort must be recent, score, rating, reviews or name")) + return + } + offset, xerr := paging.DecodeOffsetCursor(q.Cursor) + if xerr != nil { + errx.JSON(c, xerr) + return + } + leads, total, err := h.LeadFinderService.List(c.Request.Context(), orgID, q.Filter, q.Sort, limit, offset) + if err != nil { + leadsFail(c, err, "list") + return + } + var next *string + if int64(offset+len(leads)) < total { + next = paging.EncodeOffset(offset + len(leads)) + } + c.JSON(http.StatusOK, gin.H{ + "data": leads, + "pagination": gin.H{"next_cursor": next, "has_more": next != nil, "total": total}, + }) +} + +// LeadPoints returns the pins for the map. A read with a body. +func (h *Handler) LeadPoints(c *gin.Context) { + orgID, _, ok := h.leadsReady(c) + if !ok { + return + } + var q leadQuery + if err := c.ShouldBindJSON(&q); err != nil { + errx.JSON(c, errx.InvalidBody(err)) + return + } + pts, err := h.LeadFinderService.Points(c.Request.Context(), orgID, q.Filter) + if err != nil { + leadsFail(c, err, "points") + return + } + c.JSON(http.StatusOK, gin.H{"data": pts, "truncated": len(pts) >= leadfinder.PointsCap}) +} + +// LeadFacets returns the filter values for the scope. A read with a body. +func (h *Handler) LeadFacets(c *gin.Context) { + orgID, _, ok := h.leadsReady(c) + if !ok { + return + } + var q leadQuery + if err := c.ShouldBindJSON(&q); err != nil { + errx.JSON(c, errx.InvalidBody(err)) + return + } + out, err := h.LeadFinderService.Facets(c.Request.Context(), orgID, q.Filter) + if err != nil { + leadsFail(c, err, "facets") + return + } + c.JSON(http.StatusOK, out) +} + +// GetLead returns one lead. +func (h *Handler) GetLead(c *gin.Context) { + orgID, _, ok := h.leadsReady(c) + if !ok { + return + } + id, ok := leadsParamID(c, "id") + if !ok { + return + } + l, err := h.LeadFinderService.Get(c.Request.Context(), orgID, id) + if err != nil { + leadsFail(c, err, "get") + return + } + c.JSON(http.StatusOK, l) +} + +// UpdateLead edits one lead's status, notes or tags. A PATCH that sets +// values, so a retry lands on the same state. +func (h *Handler) UpdateLead(c *gin.Context) { + orgID, _, ok := h.leadsReady(c) + if !ok { + return + } + id, ok := leadsParamID(c, "id") + if !ok { + return + } + var p models.LeadPatch + if err := c.ShouldBindJSON(&p); err != nil { + errx.JSON(c, errx.InvalidBody(err)) + return + } + n, err := h.LeadFinderService.Patch(c.Request.Context(), orgID, []uuid.UUID{id}, &p) + if err != nil { + leadsFail(c, err, "update") + return + } + if n == 0 { + errx.JSON(c, errx.New(errx.NotFound, "lead not found")) + return + } + h.auditOrg(c, models.AuditActionUpdate, models.AuditEntityLead, &id, nil, nil) + l, err := h.LeadFinderService.Get(c.Request.Context(), orgID, id) + if err != nil { + leadsFail(c, err, "get") + return + } + c.JSON(http.StatusOK, l) +} + +type leadBulkPatch struct { + models.LeadSelection + models.LeadPatch +} + +// UpdateLeads edits many leads at once. Setting values and adding or removing +// tags converge, so a retry is safe. +func (h *Handler) UpdateLeads(c *gin.Context) { + orgID, _, ok := h.leadsReady(c) + if !ok { + return + } + var in leadBulkPatch + if err := c.ShouldBindJSON(&in); err != nil { + errx.JSON(c, errx.InvalidBody(err)) + return + } + ids, err := h.LeadFinderService.Resolve(c.Request.Context(), orgID, &in.LeadSelection) + if err != nil { + leadsFail(c, err, "bulk update") + return + } + n, err := h.LeadFinderService.Patch(c.Request.Context(), orgID, ids, &in.LeadPatch) + if err != nil { + leadsFail(c, err, "bulk update") + return + } + h.auditOrg(c, models.AuditActionUpdate, models.AuditEntityLead, nil, nil, map[string]string{"count": strconv.FormatInt(n, 10)}) + c.JSON(http.StatusOK, gin.H{"updated": n}) +} + +// DeleteLeads removes leads. Deleting what is already gone is a no-op, so a +// retry is safe. +func (h *Handler) DeleteLeads(c *gin.Context) { + orgID, _, ok := h.leadsReady(c) + if !ok { + return + } + var sel models.LeadSelection + if err := c.ShouldBindJSON(&sel); err != nil { + errx.JSON(c, errx.InvalidBody(err)) + return + } + ids, err := h.LeadFinderService.Resolve(c.Request.Context(), orgID, &sel) + if err != nil { + leadsFail(c, err, "delete") + return + } + n, err := h.LeadFinderService.Delete(c.Request.Context(), orgID, ids) + if err != nil { + leadsFail(c, err, "delete") + return + } + h.auditOrg(c, models.AuditActionDelete, models.AuditEntityLead, nil, nil, map[string]string{"count": strconv.FormatInt(n, 10)}) + c.JSON(http.StatusOK, gin.H{"deleted": n}) +} + +type leadEnrichRequest struct { + models.LeadSelection + Verify *bool `json:"verify"` + // People also finds the people each site names and works out their addresses. + People *bool `json:"people"` +} + +// EnrichLeads starts a background run reading the leads' websites. Send an +// Idempotency-Key to make a retry return the same run. +func (h *Handler) EnrichLeads(c *gin.Context) { + orgID, userID, ok := h.leadsReady(c) + if !ok { + return + } + var in leadEnrichRequest + if err := c.ShouldBindJSON(&in); err != nil { + errx.JSON(c, errx.InvalidBody(err)) + return + } + ids, err := h.LeadFinderService.Resolve(c.Request.Context(), orgID, &in.LeadSelection) + if err != nil { + leadsFail(c, err, "enrich") + return + } + verify := in.Verify == nil || *in.Verify + people := in.People == nil || *in.People + run, err := h.LeadFinderService.StartEnrichment(c.Request.Context(), orgID, userID, ids, verify, people) + if err != nil { + leadsFail(c, err, "enrich") + return + } + h.auditOrg(c, models.AuditActionUpdate, models.AuditEntityLead, nil, nil, + map[string]string{"enrichment_run": run.ID.String(), "count": strconv.Itoa(run.Total)}) + c.JSON(http.StatusAccepted, run) +} + +// LeadEnrichmentRuns lists the runs still going. +func (h *Handler) LeadEnrichmentRuns(c *gin.Context) { + orgID, _, ok := h.leadsReady(c) + if !ok { + return + } + runs, err := h.LeadFinderService.ActiveEnrichmentRuns(c.Request.Context(), orgID) + if err != nil { + leadsFail(c, err, "enrichment runs") + return + } + c.JSON(http.StatusOK, gin.H{"data": runs}) +} + +// LeadEnrichmentRun returns one run's progress. +func (h *Handler) LeadEnrichmentRun(c *gin.Context) { + orgID, _, ok := h.leadsReady(c) + if !ok { + return + } + id, ok := leadsParamID(c, "id") + if !ok { + return + } + run, err := h.LeadFinderService.EnrichmentRun(c.Request.Context(), orgID, id) + if err != nil { + leadsFail(c, err, "enrichment run") + return + } + c.JSON(http.StatusOK, run) +} + +// ExportLeads downloads the selected leads as CSV, XLSX or JSON. A read. +func (h *Handler) ExportLeads(c *gin.Context) { + orgID, _, ok := h.leadsReady(c) + if !ok { + return + } + var req leadfinder.ExportRequest + if err := c.ShouldBindJSON(&req); err != nil { + errx.JSON(c, errx.InvalidBody(err)) + return + } + var buf bytes.Buffer + contentType, filename, err := h.LeadFinderService.Export(c.Request.Context(), orgID, &req, &buf) + if err != nil { + leadsFail(c, err, "export") + return + } + c.Header("X-Content-Type-Options", "nosniff") + c.Header("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, filename)) + c.Data(http.StatusOK, contentType, buf.Bytes()) +} + +// AddLeadsToContacts imports the selected leads as contacts. The import +// updates a contact that already exists, so a retry adds nobody twice. +func (h *Handler) AddLeadsToContacts(c *gin.Context) { + orgID, userID, ok := h.leadsReady(c) + if !ok { + return + } + var req leadfinder.AddToContactsRequest + if err := c.ShouldBindJSON(&req); err != nil { + errx.JSON(c, errx.InvalidBody(err)) + return + } + for _, list := range [][]string{req.CampaignIDs, req.CategoryIDs, req.SegmentIDs} { + for _, id := range list { + if _, err := uuid.Parse(strings.TrimSpace(id)); err != nil { + errx.JSON(c, errx.New(errx.BadRequest, "campaign, category and segment ids must be UUIDs")) + return + } + } + } + out, err := h.LeadFinderService.AddToContacts(c.Request.Context(), orgID, userID, &req) + if err != nil { + leadsFail(c, err, "add to contacts") + return + } + meta := map[string]string{"source": "lead_finder", "imported": strconv.Itoa(out.Imported), "updated": strconv.Itoa(out.Updated)} + h.auditOrg(c, models.AuditActionCreate, models.AuditEntityContact, nil, nil, meta) + h.auditOrg(c, models.AuditActionUpdate, models.AuditEntityLead, nil, nil, meta) + c.JSON(http.StatusOK, out) +} + +// LeadSearches lists recent and saved searches. +func (h *Handler) LeadSearches(c *gin.Context) { + orgID, _, ok := h.leadsReady(c) + if !ok { + return + } + saved := false + if v := c.Query("saved"); v != "" { + b, err := strconv.ParseBool(v) + if err != nil { + errx.JSON(c, errx.New(errx.BadRequest, "saved must be true or false")) + return + } + saved = b + } + out, err := h.LeadFinderService.Searches(c.Request.Context(), orgID, saved) + if err != nil { + leadsFail(c, err, "searches") + return + } + c.JSON(http.StatusOK, gin.H{"data": out}) +} + +// UpdateLeadSearch renames or saves a search. A PATCH that sets values. +func (h *Handler) UpdateLeadSearch(c *gin.Context) { + orgID, _, ok := h.leadsReady(c) + if !ok { + return + } + id, ok := leadsParamID(c, "id") + if !ok { + return + } + var in struct { + Name *string `json:"name"` + Saved *bool `json:"saved"` + } + if err := c.ShouldBindJSON(&in); err != nil { + errx.JSON(c, errx.InvalidBody(err)) + return + } + out, err := h.LeadFinderService.UpdateSearch(c.Request.Context(), orgID, id, in.Name, in.Saved) + if err != nil { + leadsFail(c, err, "update search") + return + } + h.auditOrg(c, models.AuditActionUpdate, models.AuditEntityLeadSearch, &id, nil, nil) + c.JSON(http.StatusOK, out) +} + +// DeleteLeadSearch removes a search; its leads stay. +func (h *Handler) DeleteLeadSearch(c *gin.Context) { + orgID, _, ok := h.leadsReady(c) + if !ok { + return + } + id, ok := leadsParamID(c, "id") + if !ok { + return + } + if err := h.LeadFinderService.DeleteSearch(c.Request.Context(), orgID, id); err != nil { + leadsFail(c, err, "delete search") + return + } + h.auditOrg(c, models.AuditActionDelete, models.AuditEntityLeadSearch, &id, nil, nil) + c.Status(http.StatusNoContent) +} + +// AddLeadPerson adds someone to a lead and works out their address when none +// is given. People on a lead are matched by name, so a retry lands on the same +// person. +func (h *Handler) AddLeadPerson(c *gin.Context) { + orgID, _, ok := h.leadsReady(c) + if !ok { + return + } + id, ok := leadsParamID(c, "id") + if !ok { + return + } + var in leadfinder.PersonInput + if err := c.ShouldBindJSON(&in); err != nil { + errx.JSON(c, errx.InvalidBody(err)) + return + } + p, err := h.LeadFinderService.AddPerson(c.Request.Context(), orgID, id, in) + if err != nil { + leadsFail(c, err, "add person") + return + } + h.auditOrg(c, models.AuditActionUpdate, models.AuditEntityLead, &id, nil, map[string]string{"person": p.ID.String()}) + c.JSON(http.StatusOK, p) +} + +// UpdateLeadPerson edits someone on a lead. A PATCH that sets values. +func (h *Handler) UpdateLeadPerson(c *gin.Context) { + orgID, _, ok := h.leadsReady(c) + if !ok { + return + } + id, ok := leadsParamID(c, "id") + if !ok { + return + } + personID, ok := leadsParamID(c, "personId") + if !ok { + return + } + var patch leadfinder.PersonPatch + if err := c.ShouldBindJSON(&patch); err != nil { + errx.JSON(c, errx.InvalidBody(err)) + return + } + p, err := h.LeadFinderService.UpdatePerson(c.Request.Context(), orgID, id, personID, patch) + if err != nil { + leadsFail(c, err, "update person") + return + } + h.auditOrg(c, models.AuditActionUpdate, models.AuditEntityLead, &id, nil, map[string]string{"person": p.ID.String()}) + c.JSON(http.StatusOK, p) +} + +// DeleteLeadPerson removes someone from a lead. +func (h *Handler) DeleteLeadPerson(c *gin.Context) { + orgID, _, ok := h.leadsReady(c) + if !ok { + return + } + id, ok := leadsParamID(c, "id") + if !ok { + return + } + personID, ok := leadsParamID(c, "personId") + if !ok { + return + } + if err := h.LeadFinderService.DeletePerson(c.Request.Context(), orgID, id, personID); err != nil { + leadsFail(c, err, "delete person") + return + } + h.auditOrg(c, models.AuditActionUpdate, models.AuditEntityLead, &id, nil, map[string]string{"person": personID.String(), "removed": "true"}) + c.Status(http.StatusNoContent) +} + +// FindLeadPersonEmail works out a person's address at the lead's domain again. +// Searching again converges on the same address, so a retry is safe. +func (h *Handler) FindLeadPersonEmail(c *gin.Context) { + orgID, _, ok := h.leadsReady(c) + if !ok { + return + } + id, ok := leadsParamID(c, "id") + if !ok { + return + } + personID, ok := leadsParamID(c, "personId") + if !ok { + return + } + p, err := h.LeadFinderService.FindPersonEmail(c.Request.Context(), orgID, id, personID) + if err != nil { + leadsFail(c, err, "find person email") + return + } + h.auditOrg(c, models.AuditActionUpdate, models.AuditEntityLead, &id, nil, map[string]string{"person": p.ID.String()}) + c.JSON(http.StatusOK, p) +} diff --git a/internal/api/routes.go b/internal/api/routes.go index ed568781b..bc3ee06b4 100644 --- a/internal/api/routes.go +++ b/internal/api/routes.go @@ -904,6 +904,38 @@ func Run( } } + // Lead finder: businesses found on a map become leads, then contacts. + // Leads are prospect contacts, so the contact permissions gate them. + leads := protected.Group("/leads") + leads.Use(m.RateLimitMiddleware(models.RateLimitWrite), middleware.UUIDParams("id", "personId")) + { + viewLeads := m.RequireAccess(models.PermViewContacts, models.APIPermReadContacts) + writeLeads := m.RequireAccess(models.PermManageContacts, models.APIPermWriteContacts) + bulkLeads := m.RequireAccess(models.PermManageContacts, models.APIPermBulkContacts) + leads.GET("/config", viewLeads, h.LeadFinderConfig) + leads.GET("/geocode", viewLeads, h.LeadFinderGeocode) + leads.POST("/search", writeLeads, h.SearchLeads) + leads.POST("/query", viewLeads, h.QueryLeads) + leads.POST("/points", viewLeads, h.LeadPoints) + leads.POST("/facets", viewLeads, h.LeadFacets) + leads.POST("/export", viewLeads, h.ExportLeads) + leads.PATCH("", bulkLeads, h.UpdateLeads) + leads.DELETE("", bulkLeads, h.DeleteLeads) + leads.POST("/enrich", bulkLeads, h.EnrichLeads) + leads.GET("/enrichments", viewLeads, h.LeadEnrichmentRuns) + leads.GET("/enrichments/:id", viewLeads, h.LeadEnrichmentRun) + leads.POST("/contacts", bulkLeads, h.AddLeadsToContacts) + leads.GET("/searches", viewLeads, h.LeadSearches) + leads.PATCH("/searches/:id", writeLeads, h.UpdateLeadSearch) + leads.DELETE("/searches/:id", writeLeads, h.DeleteLeadSearch) + leads.GET("/:id", viewLeads, h.GetLead) + leads.PATCH("/:id", writeLeads, h.UpdateLead) + leads.POST("/:id/people", writeLeads, h.AddLeadPerson) + leads.PATCH("/:id/people/:personId", writeLeads, h.UpdateLeadPerson) + leads.DELETE("/:id/people/:personId", writeLeads, h.DeleteLeadPerson) + leads.POST("/:id/people/:personId/find-email", writeLeads, h.FindLeadPersonEmail) + } + contacts := protected.Group("/contacts") contacts.Use(m.RateLimitMiddleware(models.RateLimitWrite), middleware.UUIDParams("id")) { diff --git a/internal/app/appdirectory/service.go b/internal/app/appdirectory/service.go index 249cc63f9..d139c4120 100644 --- a/internal/app/appdirectory/service.go +++ b/internal/app/appdirectory/service.go @@ -54,6 +54,7 @@ var reservedSlugs = func() map[string]bool { models.IntegrationZapier, models.IntegrationMake, models.IntegrationN8N, models.IntegrationSlack, models.IntegrationDiscord, models.IntegrationCalendly, models.IntegrationCalCom, models.IntegrationGoogleSheets, models.IntegrationMillionVerifier, models.IntegrationCleanMyList, + models.IntegrationGooglePlaces, models.IntegrationFoursquare, models.IntegrationOutscraper, } { out[string(p)] = true out[strings.ReplaceAll(string(p), "_", "-")] = true diff --git a/internal/app/credits/costs.go b/internal/app/credits/costs.go index e6b921a4e..9890ab7c9 100644 --- a/internal/app/credits/costs.go +++ b/internal/app/credits/costs.go @@ -36,6 +36,18 @@ const ( // CostSpamAnalysis is one AI spam analysis of a campaign template // (POST /templates/analyze, and every Re-check after an edit). CostSpamAnalysis = 2 + + // CostLeadEnrich is reading one lead's website for emails, socials and the + // people it names; a site that never answers is refunded. + CostLeadEnrich = 1 + + // CostLeadPersonEmail is finding one named person's address at a lead's + // domain on request; refunded when no address is found. + CostLeadPersonEmail = 1 + + // CostLeadSearchPage is one page of a lead search through a provider key the + // operator pays for. A workspace's own key and OpenStreetMap cost nothing. + CostLeadSearchPage = 1 ) // Usage-based metering. The per-feature constants above are the up-front diff --git a/internal/app/integration/catalog.go b/internal/app/integration/catalog.go index bbe770b37..4284906d8 100644 --- a/internal/app/integration/catalog.go +++ b/internal/app/integration/catalog.go @@ -231,6 +231,45 @@ func Catalog() []models.IntegrationCatalogEntry { Events: ClayEvents, ActionTypes: []string{string(models.IntegrationActionClaySendRow)}, }, + { + Provider: models.IntegrationGooglePlaces, + Name: "Google Places", + Tagline: "Search Google's business listings from the lead finder map with your own key.", + Category: models.IntegrationCategoryData, + AuthMethod: string(models.IntegrationAuthAPIKey), + DocsURL: "https://docs.warmbly.com/guides/lead-finder/", + Highlights: []string{ + "Ratings, review counts, hours, phone numbers and websites", + "Billed to your Google Maps Platform account, no Warmbly credits", + "Up to 60 places per search, inside the area you draw", + }, + }, + { + Provider: models.IntegrationFoursquare, + Name: "Foursquare", + Tagline: "Search Foursquare's global places database from the lead finder map.", + Category: models.IntegrationCategoryData, + AuthMethod: string(models.IntegrationAuthAPIKey), + DocsURL: "https://docs.warmbly.com/guides/lead-finder/", + Highlights: []string{ + "Categories, chains, socials, ratings and hours", + "Billed to your Foursquare account, no Warmbly credits", + "Up to 50 places a page, paged as far as the area goes", + }, + }, + { + Provider: models.IntegrationOutscraper, + Name: "Outscraper", + Tagline: "Google Maps results with emails and socials, through your Outscraper account.", + Category: models.IntegrationCategoryData, + AuthMethod: string(models.IntegrationAuthAPIKey), + DocsURL: "https://docs.warmbly.com/guides/lead-finder/", + Highlights: []string{ + "Google Maps listings with ratings, reviews and hours", + "Emails and social profiles found from each business's domain", + "Billed to your Outscraper account, no Warmbly credits", + }, + }, // NOTE: Google Sheets is intentionally NOT a catalog integration. The // google_sheets OAuth connection still exists (it powers the on-demand diff --git a/internal/app/integration/popularity.go b/internal/app/integration/popularity.go index e8cb1ebfb..714a47463 100644 --- a/internal/app/integration/popularity.go +++ b/internal/app/integration/popularity.go @@ -32,6 +32,9 @@ var curatedOrder = []models.IntegrationProvider{ models.IntegrationMillionVerifier, models.IntegrationDiscord, models.IntegrationCleanMyList, + models.IntegrationGooglePlaces, + models.IntegrationOutscraper, + models.IntegrationFoursquare, } // popularity returns workspaces per provider from a cache. A stale cache is diff --git a/internal/app/integration/service.go b/internal/app/integration/service.go index 515bd7c88..20d787fc7 100644 --- a/internal/app/integration/service.go +++ b/internal/app/integration/service.go @@ -1844,6 +1844,8 @@ func buildDisplayFields(provider models.IntegrationProvider, config map[string]a // Credits are filled in at connect time from the provider. case models.IntegrationApollo: // The account the key acts as is filled in by the credential check. + case models.IntegrationGooglePlaces, models.IntegrationFoursquare, models.IntegrationOutscraper: + // A key and nothing to show beyond the connection itself. case models.IntegrationClay: if raw, ok := config["webhook_url"].(string); ok && raw != "" { df["webhook_host"] = urlHost(raw) diff --git a/internal/app/leadfinder/categories.go b/internal/app/leadfinder/categories.go new file mode 100644 index 000000000..a6f1c86de --- /dev/null +++ b/internal/app/leadfinder/categories.go @@ -0,0 +1,107 @@ +package leadfinder + +// Category is one kind of business the finder offers as a preset, mapped onto +// each provider's own vocabulary. +type Category struct { + ID string `json:"id"` + Label string `json:"label"` + Group string `json:"group"` + // Term is the plain search phrase for text-based providers. + Term string `json:"-"` + // OSM are Overpass tag selectors; a place matching any of them counts. + OSM []string `json:"-"` + // GoogleType is a Places (New) Table A type, empty to search by Term only. + GoogleType string `json:"-"` +} + +func cat(id, label, group, term, googleType string, osm ...string) Category { + return Category{ID: id, Label: label, Group: group, Term: term, GoogleType: googleType, OSM: osm} +} + +// Categories is every preset, in the order the dashboard lists them. +var Categories = []Category{ + cat("restaurant", "Restaurants", "Food and drink", "restaurant", "restaurant", `["amenity"="restaurant"]`), + cat("cafe", "Cafes", "Food and drink", "cafe", "cafe", `["amenity"="cafe"]`), + cat("bar", "Bars and pubs", "Food and drink", "bar", "bar", `["amenity"~"^(bar|pub)$"]`), + cat("bakery", "Bakeries", "Food and drink", "bakery", "bakery", `["shop"="bakery"]`), + cat("fast_food", "Fast food", "Food and drink", "fast food restaurant", "fast_food_restaurant", `["amenity"="fast_food"]`), + cat("catering", "Caterers", "Food and drink", "catering", "", `["craft"="caterer"]`, `["shop"="catering"]`), + + cat("dentist", "Dentists", "Health", "dentist", "dentist", `["amenity"="dentist"]`, `["healthcare"="dentist"]`), + cat("doctor", "Doctors", "Health", "doctor", "doctor", `["amenity"="doctors"]`, `["healthcare"="doctor"]`), + cat("clinic", "Clinics", "Health", "medical clinic", "", `["amenity"="clinic"]`, `["healthcare"="clinic"]`), + cat("pharmacy", "Pharmacies", "Health", "pharmacy", "pharmacy", `["amenity"="pharmacy"]`), + cat("veterinary", "Veterinarians", "Health", "veterinarian", "veterinary_care", `["amenity"="veterinary"]`), + cat("physio", "Physiotherapists", "Health", "physiotherapist", "physiotherapist", `["healthcare"="physiotherapist"]`), + cat("chiropractor", "Chiropractors", "Health", "chiropractor", "chiropractor", `["healthcare"="chiropractor"]`, `["healthcare:speciality"="chiropractic"]`), + cat("optician", "Opticians", "Health", "optician", "", `["shop"="optician"]`, `["healthcare"="optometrist"]`), + + cat("hair_salon", "Hair salons", "Beauty and fitness", "hair salon", "hair_salon", `["shop"="hairdresser"]`), + cat("beauty_salon", "Beauty salons", "Beauty and fitness", "beauty salon", "beauty_salon", `["shop"="beauty"]`), + cat("barber", "Barbers", "Beauty and fitness", "barber shop", "barber_shop", `["shop"="hairdresser"]["hairdresser"="barber"]`), + cat("spa", "Spas and massage", "Beauty and fitness", "spa", "spa", `["leisure"="spa"]`, `["shop"="massage"]`, `["amenity"="spa"]`), + cat("nail_salon", "Nail salons", "Beauty and fitness", "nail salon", "nail_salon", `["shop"="beauty"]["beauty"="nails"]`), + cat("gym", "Gyms", "Beauty and fitness", "gym", "gym", `["leisure"="fitness_centre"]`), + cat("yoga", "Yoga studios", "Beauty and fitness", "yoga studio", "yoga_studio", `["sport"="yoga"]`, `["leisure"="fitness_centre"]["sport"="yoga"]`), + cat("tattoo", "Tattoo studios", "Beauty and fitness", "tattoo studio", "", `["shop"="tattoo"]`), + + cat("plumber", "Plumbers", "Home services", "plumber", "plumber", `["craft"="plumber"]`), + cat("electrician", "Electricians", "Home services", "electrician", "electrician", `["craft"="electrician"]`), + cat("roofer", "Roofers", "Home services", "roofing contractor", "roofing_contractor", `["craft"="roofer"]`), + cat("hvac", "HVAC", "Home services", "hvac contractor", "", `["craft"="hvac"]`), + cat("painter", "Painters", "Home services", "painter", "painter", `["craft"="painter"]`), + cat("carpenter", "Carpenters", "Home services", "carpenter", "", `["craft"="carpenter"]`), + cat("locksmith", "Locksmiths", "Home services", "locksmith", "locksmith", `["shop"="locksmith"]`, `["craft"="locksmith"]`), + cat("landscaping", "Landscapers", "Home services", "landscaping", "", `["craft"="gardener"]`, `["shop"="garden_centre"]`), + cat("cleaning", "Cleaning services", "Home services", "cleaning service", "", `["shop"="dry_cleaning"]`, `["office"="cleaning"]`, `["craft"="cleaning"]`), + cat("moving", "Movers", "Home services", "moving company", "moving_company", `["office"="moving_company"]`, `["shop"="moving"]`), + + cat("lawyer", "Law firms", "Professional services", "law firm", "lawyer", `["office"="lawyer"]`), + cat("accountant", "Accountants", "Professional services", "accountant", "accounting", `["office"="accountant"]`, `["office"="tax_advisor"]`), + cat("insurance", "Insurance agents", "Professional services", "insurance agency", "insurance_agency", `["office"="insurance"]`), + cat("real_estate", "Real estate agents", "Professional services", "real estate agency", "real_estate_agency", `["office"="estate_agent"]`, `["shop"="estate_agent"]`), + cat("marketing", "Marketing agencies", "Professional services", "marketing agency", "", `["office"="advertising_agency"]`, `["office"="marketing"]`), + cat("it", "IT and software", "Professional services", "it services", "", `["office"="it"]`, `["office"="software"]`, `["craft"="computer"]`), + cat("architect", "Architects", "Professional services", "architect", "", `["office"="architect"]`), + cat("consulting", "Consultants", "Professional services", "consulting", "", `["office"="consulting"]`), + cat("financial", "Financial advisors", "Professional services", "financial advisor", "", `["office"="financial_advisor"]`, `["office"="financial"]`), + cat("coworking", "Coworking spaces", "Professional services", "coworking space", "", `["amenity"="coworking_space"]`, `["office"="coworking"]`), + + cat("car_repair", "Auto repair", "Automotive", "auto repair", "car_repair", `["shop"="car_repair"]`), + cat("car_dealer", "Car dealers", "Automotive", "car dealer", "car_dealer", `["shop"="car"]`), + cat("car_wash", "Car washes", "Automotive", "car wash", "car_wash", `["amenity"="car_wash"]`), + + cat("hotel", "Hotels", "Travel and venues", "hotel", "hotel", `["tourism"~"^(hotel|motel|guest_house)$"]`), + cat("event_venue", "Event venues", "Travel and venues", "event venue", "event_venue", `["amenity"="events_venue"]`, `["amenity"="conference_centre"]`), + cat("travel_agency", "Travel agencies", "Travel and venues", "travel agency", "travel_agency", `["shop"="travel_agency"]`, `["office"="travel_agent"]`), + + cat("florist", "Florists", "Retail", "florist", "florist", `["shop"="florist"]`), + cat("furniture", "Furniture stores", "Retail", "furniture store", "furniture_store", `["shop"="furniture"]`), + cat("hardware", "Hardware stores", "Retail", "hardware store", "hardware_store", `["shop"~"^(hardware|doityourself)$"]`), + cat("clothing", "Clothing stores", "Retail", "clothing store", "clothing_store", `["shop"~"^(clothes|boutique)$"]`), + cat("jewelry", "Jewelers", "Retail", "jewelry store", "jewelry_store", `["shop"="jewelry"]`), + cat("pet_store", "Pet stores", "Retail", "pet store", "pet_store", `["shop"="pet"]`), + cat("bookstore", "Bookstores", "Retail", "book store", "book_store", `["shop"="books"]`), + + cat("childcare", "Childcare", "Education", "child care", "child_care_agency", `["amenity"~"^(childcare|kindergarten)$"]`), + cat("driving_school", "Driving schools", "Education", "driving school", "", `["amenity"="driving_school"]`), + cat("language_school", "Language schools", "Education", "language school", "", `["amenity"="language_school"]`), + cat("tutoring", "Tutoring", "Education", "tutoring", "", `["amenity"="prep_school"]`, `["office"="tutoring"]`), + + cat("photographer", "Photographers", "Creative", "photographer", "", `["craft"="photographer"]`, `["shop"="photo"]`), + cat("print_shop", "Print shops", "Creative", "print shop", "", `["shop"="copyshop"]`, `["craft"="printer"]`), +} + +// genericOSM are the keys a named business can carry in OpenStreetMap, for a +// text search without a category. +var genericOSM = []string{`["shop"]`, `["amenity"]`, `["office"]`, `["craft"]`, `["tourism"]`, `["healthcare"]`, `["leisure"]`} + +// CategoryByID returns the preset with the id, or nil. +func CategoryByID(id string) *Category { + for i := range Categories { + if Categories[i].ID == id { + return &Categories[i] + } + } + return nil +} diff --git a/internal/app/leadfinder/contacts.go b/internal/app/leadfinder/contacts.go new file mode 100644 index 000000000..2b300fc6c --- /dev/null +++ b/internal/app/leadfinder/contacts.go @@ -0,0 +1,348 @@ +package leadfinder + +import ( + "context" + "strconv" + "strings" + + "github.com/google/uuid" + + "github.com/warmbly/warmbly/internal/app/contact" + "github.com/warmbly/warmbly/internal/errx" + "github.com/warmbly/warmbly/internal/models" + "github.com/warmbly/warmbly/internal/pkg/emailverify" +) + +// AddToContactsRequest turns selected leads, or the people at them, into contacts. +type AddToContactsRequest struct { + models.LeadSelection + CampaignIDs []string `json:"campaign_ids"` + CategoryIDs []string `json:"category_ids"` + SegmentIDs []string `json:"segment_ids"` + // VerifiedOnly keeps out every address that did not check as valid. + VerifiedOnly bool `json:"verified_only"` + // Who is "business" (each lead's own address, the default), "people" (the + // people found at each lead) or "both". + Who string `json:"who"` + // IncludeGuessed adds people whose address was worked out but not confirmed. + IncludeGuessed bool `json:"include_guessed"` + // KeepExisting leaves a contact already in the workspace as it is; it + // still gets the segments, labels and campaigns. + KeepExisting bool `json:"keep_existing"` + // SkipActiveInOtherCampaigns enrolls nobody another campaign is emailing. + SkipActiveInOtherCampaigns bool `json:"skip_active_in_other_campaigns"` +} + +// AddToContactsResult says what became of the selection. +type AddToContactsResult struct { + Selected int `json:"selected"` + Imported int `json:"imported"` + Updated int `json:"updated"` + Skipped int `json:"skipped"` + Failed int `json:"failed"` + NoEmail int `json:"no_email"` + Unverified int `json:"unverified"` + Suppressed int `json:"suppressed"` + Guessed int `json:"guessed"` + People int `json:"people"` + Errors []models.ContactImportRowError `json:"errors,omitempty"` +} + +// leadColumns are the contact fields a lead fills, in cell order. +var leadColumns = []struct { + target models.ContactImportColumnTarget + custom string + value func(l *models.Lead) string +}{ + {models.ContactImportTargetEmail, "", func(l *models.Lead) string { return l.Email }}, + {models.ContactImportTargetCompany, "", func(l *models.Lead) string { return l.Name }}, + {models.ContactImportTargetPhone, "", func(l *models.Lead) string { return l.Phone }}, + {models.ContactImportTargetVerificationStatus, "", func(l *models.Lead) string { + if e := primaryEmail(l); e != nil { + switch e.Status { + case string(emailverify.StatusValid), string(emailverify.StatusRisky), string(emailverify.StatusInvalid): + return e.Status + } + } + return "" + }}, + {models.ContactImportTargetCustom, "website", func(l *models.Lead) string { return l.Website }}, + {models.ContactImportTargetCustom, "business_category", func(l *models.Lead) string { return l.Category }}, + {models.ContactImportTargetCustom, "address", func(l *models.Lead) string { return l.Address }}, + {models.ContactImportTargetCustom, "city", func(l *models.Lead) string { return l.City }}, + {models.ContactImportTargetCustom, "state", func(l *models.Lead) string { return l.Region }}, + {models.ContactImportTargetCustom, "postcode", func(l *models.Lead) string { return l.Postcode }}, + {models.ContactImportTargetCustom, "country", func(l *models.Lead) string { return l.Country }}, + {models.ContactImportTargetCustom, "rating", func(l *models.Lead) string { return fmtFloat(l.Rating) }}, + {models.ContactImportTargetCustom, "review_count", func(l *models.Lead) string { return fmtInt(l.ReviewCount) }}, + {models.ContactImportTargetCustom, "map_url", func(l *models.Lead) string { return l.MapsURL }}, + {models.ContactImportTargetCustom, "facebook_url", social("facebook")}, + {models.ContactImportTargetCustom, "instagram_url", social("instagram")}, + {models.ContactImportTargetCustom, "linkedin_url", social("linkedin")}, + {models.ContactImportTargetCustom, "website_platform", func(l *models.Lead) string { return l.Site.Platform }}, + {models.ContactImportTargetCustom, "lead_score", func(l *models.Lead) string { return strconv.Itoa(l.Score) }}, +} + +// personColumns are the contact fields a person at a lead fills, in cell order. +var personColumns = []struct { + target models.ContactImportColumnTarget + custom string + value func(p *models.LeadPerson, l *models.Lead) string +}{ + {models.ContactImportTargetEmail, "", func(p *models.LeadPerson, _ *models.Lead) string { return p.Email }}, + {models.ContactImportTargetFirstName, "", func(p *models.LeadPerson, _ *models.Lead) string { return p.FirstName }}, + {models.ContactImportTargetLastName, "", func(p *models.LeadPerson, _ *models.Lead) string { return p.LastName }}, + {models.ContactImportTargetCompany, "", func(_ *models.LeadPerson, l *models.Lead) string { return l.Name }}, + {models.ContactImportTargetPhone, "", func(p *models.LeadPerson, l *models.Lead) string { return firstNonEmpty(p.Phone, l.Phone) }}, + {models.ContactImportTargetVerificationStatus, "", func(p *models.LeadPerson, _ *models.Lead) string { + switch p.EmailStatus { + case string(emailverify.StatusValid), string(emailverify.StatusRisky), string(emailverify.StatusInvalid): + return p.EmailStatus + } + return "" + }}, + {models.ContactImportTargetCustom, "job_title", func(p *models.LeadPerson, _ *models.Lead) string { return p.Title }}, + {models.ContactImportTargetCustom, "seniority", func(p *models.LeadPerson, _ *models.Lead) string { return string(p.Seniority) }}, + {models.ContactImportTargetCustom, "linkedin_url", func(p *models.LeadPerson, _ *models.Lead) string { return p.LinkedInURL }}, + {models.ContactImportTargetCustom, "company_linkedin_url", func(_ *models.LeadPerson, l *models.Lead) string { return l.Socials["linkedin"] }}, + {models.ContactImportTargetCustom, "website", func(_ *models.LeadPerson, l *models.Lead) string { return l.Website }}, + {models.ContactImportTargetCustom, "business_category", func(_ *models.LeadPerson, l *models.Lead) string { return l.Category }}, + {models.ContactImportTargetCustom, "address", func(_ *models.LeadPerson, l *models.Lead) string { return l.Address }}, + {models.ContactImportTargetCustom, "city", func(_ *models.LeadPerson, l *models.Lead) string { return l.City }}, + {models.ContactImportTargetCustom, "state", func(_ *models.LeadPerson, l *models.Lead) string { return l.Region }}, + {models.ContactImportTargetCustom, "country", func(_ *models.LeadPerson, l *models.Lead) string { return l.Country }}, + {models.ContactImportTargetCustom, "map_url", func(_ *models.LeadPerson, l *models.Lead) string { return l.MapsURL }}, + {models.ContactImportTargetCustom, "lead_score", func(_ *models.LeadPerson, l *models.Lead) string { return strconv.Itoa(l.Score) }}, +} + +// AddToContacts imports the selected leads' addresses, the people at them, or +// both as contacts, optionally straight into campaigns, categories and +// segments. People go first, so an owner whose address is also the +// business's lands as a person. +func (s *Service) AddToContacts(ctx context.Context, orgID, userID uuid.UUID, req *AddToContactsRequest) (*AddToContactsResult, error) { + who := strings.ToLower(strings.TrimSpace(req.Who)) + if who == "" { + who = "business" + } + if who != "business" && who != "people" && who != "both" { + return nil, errx.New(errx.BadRequest, "who must be business, people or both") + } + ids, err := s.Resolve(ctx, orgID, &req.LeadSelection) + if err != nil { + return nil, err + } + res := &AddToContactsResult{Selected: len(ids)} + var leads []models.Lead + for start := 0; start < len(ids); start += 500 { + batch, err := s.Repo.LeadsByIDs(ctx, orgID, ids[start:min(start+500, len(ids))]) + if err != nil { + return nil, err + } + if who != "business" { + people, err := s.Repo.PeopleForLeads(ctx, orgID, ids[start:min(start+500, len(ids))]) + if err != nil { + return nil, err + } + for i := range batch { + batch[i].People = people[batch[i].ID] + } + } + leads = append(leads, batch...) + } + var emails []string + for _, l := range leads { + if l.Email != "" { + emails = append(emails, l.Email) + } + for _, p := range l.People { + if p.Email != "" { + emails = append(emails, p.Email) + } + } + } + suppressed, err := s.Repo.SuppressedEmails(ctx, orgID, emails) + if err != nil { + return nil, err + } + seen := map[string]bool{} + usable := func(email, status string) bool { + switch { + case email == "": + res.NoEmail++ + case suppressed[email] || status == "suppressed": + res.Suppressed++ + case status == string(emailverify.StatusInvalid): + res.Unverified++ + case status == models.LeadPersonStatusGuessed && !req.IncludeGuessed: + res.Guessed++ + case req.VerifiedOnly && status != string(emailverify.StatusValid): + res.Unverified++ + case seen[email]: + res.Skipped++ + default: + seen[email] = true + return true + } + return false + } + + opts := s.importOptions(req) + if who != "business" { + type pick struct { + person *models.LeadPerson + lead *models.Lead + } + var picks []pick + for i := range leads { + l := &leads[i] + for k := range l.People { + p := &l.People[k] + res.People++ + if usable(p.Email, p.EmailStatus) { + picks = append(picks, pick{p, l}) + } + } + } + if len(picks) > 0 { + cells := make([][]string, len(picks)) + for i, pk := range picks { + row := make([]string, len(personColumns)) + for j, c := range personColumns { + row[j] = truncate(c.value(pk.person, pk.lead), 500) + } + cells[i] = row + } + mapping := make([]models.ContactImportColumnMapping, len(personColumns)) + for i, c := range personColumns { + mapping[i] = models.ContactImportColumnMapping{Index: i, Target: c.target, CustomKey: c.custom} + } + contacts, err := s.runImport(ctx, orgID, userID, mapping, cells, opts, res) + if err != nil { + return nil, err + } + links := map[uuid.UUID]uuid.UUID{} + leadLinks := map[uuid.UUID]uuid.UUID{} + for i, pk := range picks { + if c, ok := contacts[i]; ok { + links[pk.person.ID] = c + if _, done := leadLinks[pk.lead.ID]; !done && pk.lead.ContactID == nil { + leadLinks[pk.lead.ID] = c + } + } + } + if err := s.Repo.LinkPersonContacts(ctx, orgID, links); err != nil { + return res, errx.New(errx.Internal, "the contacts were added but could not be linked back to their people") + } + if who == "people" { + // The lead counts as reached through its first person. + if err := s.Repo.LinkContacts(ctx, orgID, leadLinks); err != nil { + return res, errx.New(errx.Internal, "the contacts were added but could not be linked back to their leads") + } + } + } + } + if who == "people" { + return res, nil + } + + var fresh []*models.Lead + for i := range leads { + l := &leads[i] + status := "" + if e := primaryEmail(l); e != nil { + status = e.Status + } + if usable(l.Email, status) { + fresh = append(fresh, l) + } + } + if len(fresh) == 0 { + return res, nil + } + mapping := make([]models.ContactImportColumnMapping, len(leadColumns)) + for i, c := range leadColumns { + mapping[i] = models.ContactImportColumnMapping{Index: i, Target: c.target, CustomKey: c.custom} + } + cells := make([][]string, len(fresh)) + for i, l := range fresh { + row := make([]string, len(leadColumns)) + for j, c := range leadColumns { + row[j] = truncate(c.value(l), 500) + } + cells[i] = row + } + contacts, err := s.runImport(ctx, orgID, userID, mapping, cells, opts, res) + if err != nil { + return nil, err + } + links := map[uuid.UUID]uuid.UUID{} + for i, l := range fresh { + if c, ok := contacts[i]; ok { + links[l.ID] = c + } + } + if err := s.Repo.LinkContacts(ctx, orgID, links); err != nil { + return res, errx.New(errx.Internal, "the contacts were added but could not be linked back to their leads") + } + return res, nil +} + +func (s *Service) importOptions(req *AddToContactsRequest) *models.ContactImportCommit { + subscribed := true + dedup := models.ContactImportDedupUpdate + if req.KeepExisting { + dedup = models.ContactImportDedupSkip + } + return &models.ContactImportCommit{ + Dedup: dedup, + CategoryIDs: req.CategoryIDs, + CampaignIDs: req.CampaignIDs, + SegmentIDs: req.SegmentIDs, + SkipActiveInOtherCampaigns: req.SkipActiveInOtherCampaigns, + SubscribedDefault: &subscribed, + Source: models.ContactSourceLeadFinder, + SourceDetail: "Lead finder", + } +} + +// runImport imports rows through the contact importer, adds its counts to res +// and returns the contact each row (by index) became. +func (s *Service) runImport(ctx context.Context, orgID, userID uuid.UUID, mapping []models.ContactImportColumnMapping, cells [][]string, base *models.ContactImportCommit, res *AddToContactsResult) (map[int]uuid.UUID, error) { + opts := *base + opts.Mapping = mapping + rows := make([]contact.ImportRow, len(cells)) + for i, c := range cells { + rows[i] = contact.ImportRow{Line: i + 1, Cells: c} + } + sink := &outcomeSink{outcomes: map[int]models.ContactImportRowOutcome{}} + result, xerr := s.Contacts.RunImport(ctx, userID.String(), orgID, rows, &opts, sink, nil) + if xerr != nil { + return nil, xerr + } + res.Imported += result.Imported + res.Updated += result.Updated + res.Failed += result.Failed + res.Skipped += result.Skipped + res.Errors = append(res.Errors, result.Errors...) + out := map[int]uuid.UUID{} + for i := range cells { + if o, ok := sink.outcomes[i+1]; ok && o.ContactID != nil && o.Status != models.ContactImportRowFailed { + out[i] = *o.ContactID + } + } + return out, nil +} + +// outcomeSink keeps every row outcome of an import by line. +type outcomeSink struct { + outcomes map[int]models.ContactImportRowOutcome +} + +func (c *outcomeSink) Settle(_ context.Context, outcomes []models.ContactImportRowOutcome) error { + for _, o := range outcomes { + c.outcomes[o.Line] = o + } + return nil +} + +func (c *outcomeSink) Cancelled(context.Context) bool { return false } diff --git a/internal/app/leadfinder/crawl.go b/internal/app/leadfinder/crawl.go new file mode 100644 index 000000000..91e8d0a16 --- /dev/null +++ b/internal/app/leadfinder/crawl.go @@ -0,0 +1,709 @@ +package leadfinder + +import ( + "context" + "encoding/hex" + "errors" + "io" + "mime" + "net/http" + "net/url" + "regexp" + "sort" + "strconv" + "strings" + "time" + "unicode/utf8" + + "golang.org/x/net/html" + "golang.org/x/net/publicsuffix" + + "github.com/warmbly/warmbly/internal/models" + "github.com/warmbly/warmbly/internal/pkg/safehttp" +) + +const ( + crawlMaxPages = 7 + crawlMaxBytes = 1536 << 10 + crawlPageTimeout = 12 * time.Second + crawlMaxEmails = 8 + // crawlMaxAddrs bounds every address read, personal ones included. + crawlMaxAddrs = 60 +) + +// FoundEmail is one address read off a page. +type FoundEmail struct { + Email string + URL string +} + +// CrawlResult is everything reading one business's website found. +type CrawlResult struct { + Emails []FoundEmail + Socials map[string]string + Site models.LeadSite + // People are those the site names, with any address it published for them. + People []FoundPerson + // Domain is the site's own registrable domain, after redirects. + Domain string +} + +// Crawler reads a business's own public pages, the way a visitor would: the +// home page and the few pages that list contact details, nothing robots.txt +// keeps out. +type Crawler struct { + client *http.Client + userAgent string + now func() time.Time + lookup func(ctx context.Context, host string) ([]string, error) +} + +// NewCrawler builds a crawler over the SSRF-hardened transport. Plain-http +// sites are common among small businesses, so port 80 is allowed. +func NewCrawler(userAgent string) *Crawler { + return &Crawler{ + userAgent: userAgent, + now: time.Now, + lookup: defaultLookup, + client: &http.Client{ + Timeout: crawlPageTimeout, + Transport: safehttp.NewTransport("80", "443"), + CheckRedirect: func(req *http.Request, via []*http.Request) error { + if len(via) >= 5 { + return errors.New("too many redirects") + } + if (req.URL.Scheme != "http" && req.URL.Scheme != "https") || req.URL.User != nil { + return errors.New("redirect is not allowed") + } + return nil + }, + }, + } +} + +// contactPath spots links worth following for contact details, in the +// languages the finder is most used in. +var contactPath = regexp.MustCompile(`(?i)(contact|kontakt|contacto|contatti|contato|about|uber-uns|ueber-uns|about-us|team|staff|people|leadership|management|meet|doctors|dentists|attorneys|lawyers|providers|physicians|agents|founders|who-we-are|mitarbeiter|equipo|equipe|squadra|impressum|imprint|legal|mentions|aviso-legal|location|find-us|reach)`) + +// Crawl reads the site at website. A site that cannot be reached is a result, +// not an error: Site.Reachable is false and Site.Error says why. +func (c *Crawler) Crawl(ctx context.Context, website string) (*CrawlResult, error) { + start, err := url.Parse(website) + if err != nil || start.Hostname() == "" { + return nil, errors.New("the website address is not valid") + } + now := c.now() + res := &CrawlResult{Socials: map[string]string{}, Site: models.LeadSite{CheckedAt: &now}} + rules := c.robots(ctx, start) + + home, err := c.fetch(ctx, start.String(), rules) + if err != nil && start.Scheme == "https" { + alt := *start + alt.Scheme = "http" + // The http origin answers for itself, here and for every page read after. + altRules := c.robots(ctx, &alt) + if h, e := c.fetch(ctx, alt.String(), altRules); e == nil { + home, err, rules = h, nil, altRules + } + } + if err != nil { + res.Site.Error = err.Error() + return res, nil + } + res.Site.Reachable = true + res.Site.FinalURL = home.url.String() + res.Site.HTTPS = home.url.Scheme == "https" + res.Site.Title = home.title + res.Site.Description = home.description + res.Site.Platform, res.Site.Signals = detectSite(home, now) + pages := []*page{home} + + baseDomain := registrable(home.url.Hostname()) + var follow []string + seen := map[string]bool{normURL(home.url): true} + for _, l := range home.links { + u, err := home.url.Parse(l.href) + if err != nil || (u.Scheme != "http" && u.Scheme != "https") || registrable(u.Hostname()) != baseDomain { + continue + } + u.Fragment = "" + key := normURL(u) + if seen[key] || !(contactPath.MatchString(u.Path) || contactPath.MatchString(l.text)) { + continue + } + seen[key] = true + follow = append(follow, u.String()) + } + // Contact pages first, then about, then the rest. + sort.SliceStable(follow, func(i, j int) bool { return contactRank(follow[i]) < contactRank(follow[j]) }) + for _, target := range follow { + if len(pages) >= crawlMaxPages || ctx.Err() != nil { + break + } + if p, err := c.fetch(ctx, target, rules); err == nil { + pages = append(pages, p) + } + } + res.Site.Pages = len(pages) + res.Domain = baseDomain + + emailSeen := map[string]bool{} + phoneSeen := map[string]bool{} + var addrs []FoundEmail + var found []FoundPerson + personal := "" + for _, p := range pages { + for _, e := range p.emails { + if !emailSeen[e] && len(addrs) < crawlMaxAddrs { + emailSeen[e] = true + addrs = append(addrs, FoundEmail{Email: e, URL: p.url.String()}) + } + } + found = append(found, extractPeople(p)...) + for _, ph := range p.phones { + if !phoneSeen[ph] && len(res.Site.Phones) < 3 { + phoneSeen[ph] = true + res.Site.Phones = append(res.Site.Phones, ph) + } + } + for _, l := range p.links { + u, err := p.url.Parse(l.href) + if err != nil { + continue + } + if kind := socialKind(u.String()); kind != "" && res.Socials[kind] == "" { + u.RawQuery, u.Fragment = "", "" + // A profile on a team page is a person's, not the business's. + if kind == "linkedin" && strings.HasPrefix(strings.Trim(u.Path, "/"), "in/") { + if personal == "" { + personal = u.String() + } + continue + } + res.Socials[kind] = u.String() + } + } + } + if res.Socials["linkedin"] == "" && personal != "" { + res.Socials["linkedin"] = personal + } + people, pattern := attachEmails(mergePeople(found), addrs, baseDomain) + res.People = mergePeople(people) + res.Site.EmailPattern = pattern + // The business's own list leads with the addresses no one person owns. + owned := map[string]bool{} + for _, p := range res.People { + owned[p.Email] = true + } + for _, own := range []bool{false, true} { + for _, e := range addrs { + if len(res.Emails) < crawlMaxEmails && owned[e.Email] == own { + res.Emails = append(res.Emails, e) + } + } + } + return res, nil +} + +// teamPath names the pages that list the people who work somewhere. +var teamPath = regexp.MustCompile(`(?i)(team|staff|people|leadership|management|meet|doctors|dentists|attorneys|lawyers|providers|physicians|agents|founders|who-we-are|mitarbeiter|equipo|equipe|squadra)`) + +func contactRank(u string) int { + l := strings.ToLower(u) + switch { + case strings.Contains(l, "contact") || strings.Contains(l, "kontakt") || strings.Contains(l, "contato"): + return 0 + case teamPath.MatchString(l): + return 1 + case imprintURL(l): + return 2 + case strings.Contains(l, "about"): + return 3 + } + return 4 +} + +func imprintURL(u string) bool { + l := strings.ToLower(u) + return strings.Contains(l, "impressum") || strings.Contains(l, "imprint") || strings.Contains(l, "legal") || strings.Contains(l, "mentions") +} + +func registrable(host string) string { + host = strings.ToLower(host) + d, err := publicsuffix.EffectiveTLDPlusOne(host) + if err != nil { + return strings.TrimPrefix(host, "www.") + } + return d +} + +func normURL(u *url.URL) string { + return strings.TrimPrefix(strings.ToLower(u.Hostname()), "www.") + strings.TrimSuffix(u.EscapedPath(), "/") + "?" + u.RawQuery +} + +type link struct { + href string + text string +} + +type page struct { + url *url.URL + title string + description string + generator string + raw string + links []link + emails []string + phones []string + hasViewport bool + // segments is the visible text, one entry per element, in page order. + segments []string + jsonld []string +} + +// inlineTags format text without starting a new piece of it. +var inlineTags = map[string]bool{"em": true, "i": true, "small": true, "sup": true, "sub": true, "abbr": true, "mark": true, "u": true} + +func (c *Crawler) fetch(ctx context.Context, target string, rules *robotsRules) (*page, error) { + u, err := url.Parse(target) + if err != nil { + return nil, err + } + if !rules.allowed(u) { + return nil, errors.New("the site's robots.txt asks crawlers not to read this page") + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, target, nil) + if err != nil { + return nil, err + } + req.Header.Set("User-Agent", c.userAgent) + req.Header.Set("Accept", "text/html,application/xhtml+xml;q=0.9,*/*;q=0.5") + resp, err := c.client.Do(req) + if err != nil { + if errors.Is(err, safehttp.ErrBlockedAddress) { + return nil, errors.New("the website points at a private address") + } + return nil, errors.New("the website did not answer") + } + defer resp.Body.Close() + if resp.StatusCode >= 400 { + return nil, errors.New("the website answered " + strconv.Itoa(resp.StatusCode)) + } + if ct := resp.Header.Get("Content-Type"); ct != "" { + mt, _, _ := mime.ParseMediaType(ct) + if mt != "text/html" && mt != "application/xhtml+xml" { + return nil, errors.New("the website did not send a web page") + } + } + body, err := io.ReadAll(io.LimitReader(resp.Body, crawlMaxBytes)) + if err != nil { + return nil, errors.New("the website stopped mid-page") + } + p := parsePage(string(body)) + p.url = resp.Request.URL + return p, nil +} + +var ( + emailInText = regexp.MustCompile(`[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9\-]+(?:\.[a-zA-Z0-9\-]+)*\.[a-zA-Z]{2,24}`) + obfuscAt = regexp.MustCompile(`(?i)\s*[\[\(\{<]\s*(?:at|@)\s*[\]\)\}>]\s*`) + obfuscDot = regexp.MustCompile(`(?i)\s*[\[\(\{<]\s*(?:dot|\.)\s*[\]\)\}>]\s*`) + telDigits = regexp.MustCompile(`[^0-9+]`) +) + +// junkEmailDomains are hosts that show up in page source but never belong to +// the business: tracking, builders and placeholders. +var junkEmailDomains = map[string]bool{ + "sentry.io": true, "wixpress.com": true, "sentry.wixpress.com": true, "sentry-next.wixpress.com": true, + "example.com": true, "example.org": true, "domain.com": true, "yourdomain.com": true, "yoursite.com": true, + "email.com": true, "website.com": true, "company.com": true, "mysite.com": true, "test.com": true, + "godaddy.com": true, "squarespace.com": true, "wix.com": true, "shopify.com": true, "wordpress.com": true, + "sentry.zendesk.com": true, "addresshere.com": true, +} + +var junkEmailSuffix = []string{".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg", ".css", ".js", ".ico", ".avif"} + +var hexLocal = regexp.MustCompile(`^[0-9a-f]{16,}$`) + +// acceptEmail filters what the page extraction found down to real addresses. +func acceptEmail(raw string) string { + e := cleanEmail(raw) + if e == "" { + return "" + } + for _, s := range junkEmailSuffix { + if strings.HasSuffix(e, s) { + return "" + } + } + at := strings.LastIndexByte(e, '@') + local, host := e[:at], e[at+1:] + if junkEmailDomains[host] || hexLocal.MatchString(local) || strings.Contains(local, "..") { + return "" + } + switch local { + case "you", "your", "name", "yourname", "email", "user", "username", "someone", "john.doe", "johndoe", "firstname.lastname": + return "" + } + return e +} + +// decodeCloudflareEmail reverses Cloudflare's email obfuscation. +func decodeCloudflareEmail(enc string) string { + b, err := hex.DecodeString(enc) + if err != nil || len(b) < 2 { + return "" + } + key := b[0] + out := make([]byte, len(b)-1) + for i := 1; i < len(b); i++ { + out[i-1] = b[i] ^ key + } + return string(out) +} + +func parsePage(src string) *page { + p := &page{raw: strings.ToLower(src)} + z := html.NewTokenizer(strings.NewReader(src)) + var text, seg, ld strings.Builder + var inTitle, skip, inLD bool + cur := -1 + flush := func() { + t := strings.Join(strings.Fields(seg.String()), " ") + seg.Reset() + if t != "" && len(p.segments) < segmentsMax && utf8.RuneCountInString(t) <= segmentMax { + p.segments = append(p.segments, t) + } + } + emails := map[string]bool{} + addEmail := func(raw string) { + if e := acceptEmail(raw); e != "" && !emails[e] { + emails[e] = true + p.emails = append(p.emails, e) + } + } + for { + tt := z.Next() + if tt == html.ErrorToken { + break + } + switch tt { + case html.StartTagToken, html.SelfClosingTagToken: + name, hasAttr := z.TagName() + tag := string(name) + if !inlineTags[tag] { + flush() + } + attrs := map[string]string{} + for hasAttr { + var k, v []byte + k, v, hasAttr = z.TagAttr() + attrs[string(k)] = string(v) + } + if enc := attrs["data-cfemail"]; enc != "" { + addEmail(decodeCloudflareEmail(enc)) + } + switch tag { + case "title": + inTitle = true + case "script", "style", "noscript", "svg": + skip = tt == html.StartTagToken + inLD = skip && tag == "script" && strings.Contains(strings.ToLower(attrs["type"]), "ld+json") + case "meta": + switch strings.ToLower(attrs["name"]) { + case "description": + p.description = strings.TrimSpace(attrs["content"]) + case "generator": + p.generator = strings.TrimSpace(attrs["content"]) + case "viewport": + p.hasViewport = true + } + if strings.EqualFold(attrs["property"], "og:description") && p.description == "" { + p.description = strings.TrimSpace(attrs["content"]) + } + case "a": + href := strings.TrimSpace(attrs["href"]) + lower := strings.ToLower(href) + switch { + case strings.HasPrefix(lower, "mailto:"): + addr, _ := url.QueryUnescape(href[len("mailto:"):]) + for _, part := range strings.Split(addr, ",") { + addEmail(part) + } + // Kept as a link too: its text may name the person it reaches. + p.links = append(p.links, link{href: href}) + if tt == html.StartTagToken { + cur = len(p.links) - 1 + } + case strings.HasPrefix(lower, "tel:"): + if d := telDigits.ReplaceAllString(href[4:], ""); len(d) >= 7 { + p.phones = append(p.phones, d) + } + case strings.Contains(lower, "/cdn-cgi/l/email-protection#"): + // Sliced at the fragment of href itself: lowercasing can change byte lengths. + if i := strings.IndexByte(href, '#'); i >= 0 { + addEmail(decodeCloudflareEmail(href[i+1:])) + } + case href != "" && !strings.HasPrefix(lower, "javascript:"): + p.links = append(p.links, link{href: href}) + if tt == html.StartTagToken { + cur = len(p.links) - 1 + } + } + } + case html.EndTagToken: + name, _ := z.TagName() + if !inlineTags[string(name)] { + flush() + } + switch string(name) { + case "title": + inTitle = false + case "script", "style", "noscript", "svg": + if inLD && ld.Len() > 0 && len(p.jsonld) < 20 { + p.jsonld = append(p.jsonld, ld.String()) + } + ld.Reset() + skip, inLD = false, false + case "a": + cur = -1 + } + case html.TextToken: + if inLD { + if ld.Len() < 256<<10 { + ld.Write(z.Text()) + } + continue + } + if skip { + continue + } + t := string(z.Text()) + if inTitle && p.title == "" { + p.title = strings.TrimSpace(t) + } + if cur >= 0 && len(p.links[cur].text) < 80 { + p.links[cur].text += strings.TrimSpace(t) + } + text.WriteString(t) + text.WriteByte(' ') + seg.WriteString(t) + seg.WriteByte(' ') + } + } + flush() + plain := obfuscDot.ReplaceAllString(obfuscAt.ReplaceAllString(text.String(), "@"), ".") + for _, m := range emailInText.FindAllString(plain, 50) { + addEmail(m) + } + if len(p.title) > 200 { + p.title = p.title[:200] + } + if len(p.description) > 400 { + p.description = p.description[:400] + } + return p +} + +type signature struct { + name string + needles []string +} + +var platforms = []signature{ + {"Shopify", []string{"cdn.shopify.com", "myshopify.com"}}, + {"Wix", []string{"static.wixstatic.com", "wix.com website builder"}}, + {"Squarespace", []string{"static1.squarespace.com", "squarespace.com"}}, + {"Webflow", []string{"data-wf-site", "webflow.com"}}, + {"Framer", []string{"framerusercontent.com"}}, + {"Duda", []string{"multiscreensite.com", "dudaone"}}, + {"GoDaddy Website Builder", []string{"img1.wsimg.com"}}, + {"Weebly", []string{"weebly.com"}}, + {"HubSpot CMS", []string{"hs-sites.com", "hubspot cms"}}, + {"WordPress", []string{"wp-content/", "wp-includes/"}}, + {"Joomla", []string{"/media/jui/", "joomla"}}, + {"Drupal", []string{"drupal-settings-json", "/sites/default/files/"}}, +} + +var signals = []signature{ + {"Google Analytics", []string{"google-analytics.com/", "gtag('config'", "gtag(\"config\""}}, + {"Google Tag Manager", []string{"googletagmanager.com/gtm.js"}}, + {"Meta Pixel", []string{"connect.facebook.net", "fbq('init'"}}, + {"Online booking", []string{"calendly.com", "acuityscheduling.com", "booksy.com", "fresha.com", "opentable.com", "resy.com", "mindbodyonline.com", "squareup.com/appointments", "zocdoc.com", "setmore.com", "simplybook"}}, + {"Live chat", []string{"widget.intercom.io", "js.driftt.com", "embed.tawk.to", "client.crisp.chat", "livechatinc.com", "static.zdassets.com", "tidio"}}, + {"Online store", []string{"cdn.shopify.com", "woocommerce", "ecwid.com", "bigcommerce.com"}}, + {"Contact form", []string{"wpcf7", "gform_wrapper", "type=\"email\"", "hs-form", "formspree.io"}}, +} + +var copyrightYear = regexp.MustCompile(`(?:©|©|copyright)\s*(?:\d{4}\s*[-–]\s*)?((?:19|20)\d{2})`) + +// detectSite names the platform a site runs on and the signals a prospector +// reads from it, digital gaps included. +func detectSite(p *page, now time.Time) (string, []string) { + platform := "" + gen := strings.ToLower(p.generator) + for _, s := range platforms { + if strings.Contains(gen, strings.ToLower(s.name)) { + platform = s.name + break + } + for _, n := range s.needles { + if strings.Contains(p.raw, n) { + platform = s.name + break + } + } + if platform != "" { + break + } + } + var out []string + for _, s := range signals { + for _, n := range s.needles { + if strings.Contains(p.raw, n) { + out = append(out, s.name) + break + } + } + } + if p.url != nil && p.url.Scheme != "https" { + out = append(out, "No HTTPS") + } + if !p.hasViewport { + out = append(out, "Not mobile friendly") + } + if m := copyrightYear.FindAllStringSubmatch(p.raw, -1); len(m) > 0 { + latest := 0 + for _, g := range m { + if y, _ := strconv.Atoi(g[1]); y > latest && y <= now.Year() { + latest = y + } + } + if latest > 0 && latest < now.Year()-2 { + out = append(out, "Outdated footer ("+strconv.Itoa(latest)+")") + } + } + if !containsStr(out, "Google Analytics") && !containsStr(out, "Google Tag Manager") && !containsStr(out, "Meta Pixel") { + out = append(out, "No analytics") + } + return platform, out +} + +func containsStr(xs []string, v string) bool { + for _, x := range xs { + if x == v { + return true + } + } + return false +} + +// --- robots.txt ------------------------------------------------------------- + +type robotsRule struct { + allow bool + path string +} + +type robotsRules struct { + rules []robotsRule +} + +// robots reads the site's robots.txt for our agent, falling back to "*". A +// missing or unreadable file allows everything, as crawlers conventionally do. +func (c *Crawler) robots(ctx context.Context, site *url.URL) *robotsRules { + u := url.URL{Scheme: site.Scheme, Host: site.Host, Path: "/robots.txt"} + req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil) + if err != nil { + return &robotsRules{} + } + req.Header.Set("User-Agent", c.userAgent) + resp, err := c.client.Do(req) + if err != nil { + return &robotsRules{} + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return &robotsRules{} + } + body, _ := io.ReadAll(io.LimitReader(resp.Body, 256<<10)) + return parseRobots(string(body), "warmblybot") +} + +func parseRobots(src, agent string) *robotsRules { + groups := map[string][]robotsRule{} + var current []string + lastWasAgent := false + for _, line := range strings.Split(src, "\n") { + if i := strings.IndexByte(line, '#'); i >= 0 { + line = line[:i] + } + k, v, ok := strings.Cut(line, ":") + if !ok { + continue + } + k = strings.ToLower(strings.TrimSpace(k)) + v = strings.TrimSpace(v) + switch k { + case "user-agent": + if !lastWasAgent { + current = nil + } + current = append(current, strings.ToLower(v)) + lastWasAgent = true + case "allow", "disallow": + lastWasAgent = false + if v == "" { + continue + } + for _, a := range current { + groups[a] = append(groups[a], robotsRule{allow: k == "allow", path: v}) + } + default: + lastWasAgent = false + } + } + if r, ok := groups[agent]; ok { + return &robotsRules{rules: r} + } + return &robotsRules{rules: groups["*"]} +} + +// allowed applies the longest matching rule; allow wins a tie. +func (r *robotsRules) allowed(u *url.URL) bool { + if r == nil { + return true + } + path := u.EscapedPath() + if path == "" { + path = "/" + } + if u.RawQuery != "" { + path += "?" + u.RawQuery + } + best, allow := -1, true + for _, rule := range r.rules { + if robotsMatch(rule.path, path) { + n := len(rule.path) + if n > best || (n == best && rule.allow) { + best, allow = n, rule.allow + } + } + } + return allow +} + +func robotsMatch(pattern, path string) bool { + anchored := strings.HasSuffix(pattern, "$") + pattern = strings.TrimSuffix(pattern, "$") + parts := strings.Split(pattern, "*") + pos := 0 + for i, part := range parts { + idx := strings.Index(path[pos:], part) + if idx < 0 || (i == 0 && idx != 0) { + return false + } + pos += idx + len(part) + } + return !anchored || pos == len(path) || strings.HasSuffix(pattern, "*") +} diff --git a/internal/app/leadfinder/enrich.go b/internal/app/leadfinder/enrich.go new file mode 100644 index 000000000..1962fa718 --- /dev/null +++ b/internal/app/leadfinder/enrich.go @@ -0,0 +1,356 @@ +package leadfinder + +import ( + "context" + "errors" + "sort" + "strings" + "sync" + "time" + + "github.com/google/uuid" + "github.com/rs/zerolog/log" + + "github.com/warmbly/warmbly/internal/app/credits" + "github.com/warmbly/warmbly/internal/errx" + "github.com/warmbly/warmbly/internal/models" + "github.com/warmbly/warmbly/internal/pkg/emailverify" +) + +const ( + enrichChunk = 24 + enrichParallel = 6 + enrichVerifyMax = 3 + enrichRunTimeout = 45 * time.Minute + enrichLeadTimeout = 50 * time.Second +) + +// errOutOfCredits stops a run when the workspace cannot pay for the next site. +var errOutOfCredits = errors.New("the workspace ran out of credits; the rest of the leads were left as they were") + +// AuditLogger records a finished run so every teammate's dashboard refreshes. +type AuditLogger interface { + LogAction(ctx context.Context, orgID, actorID uuid.UUID, action models.AuditAction, entityType models.AuditEntityType, entityID *uuid.UUID, ipAddress, userAgent string, changes, metadata map[string]string) +} + +// StartEnrichment queues a run reading the leads' websites and starts it in +// the background. +func (s *Service) StartEnrichment(ctx context.Context, orgID, userID uuid.UUID, ids []uuid.UUID, verify, people bool) (*models.LeadEnrichmentRun, error) { + if len(ids) == 0 { + return nil, errx.New(errx.BadRequest, "select at least one lead to enrich") + } + uid := userID + run := &models.LeadEnrichmentRun{OrganizationID: orgID, RequestedByUserID: &uid, LeadIDs: ids, Verify: verify, People: people, Total: len(ids)} + if err := s.Repo.CreateEnrichmentRun(ctx, run); err != nil { + return nil, err + } + if err := s.Repo.MarkQueued(ctx, orgID, ids); err != nil { + return nil, err + } + go func(id uuid.UUID) { + bg, cancel := context.WithTimeout(context.Background(), enrichRunTimeout) + defer cancel() + s.runEnrichment(bg, id) + }(run.ID) + return run, nil +} + +// EnrichmentRun returns one run's progress. +func (s *Service) EnrichmentRun(ctx context.Context, orgID, id uuid.UUID) (*models.LeadEnrichmentRun, error) { + run, err := s.Repo.GetEnrichmentRun(ctx, orgID, id) + if err != nil { + return nil, err + } + if run == nil { + return nil, errx.New(errx.NotFound, "enrichment run not found") + } + return run, nil +} + +// ActiveEnrichmentRuns lists the runs still going. +func (s *Service) ActiveEnrichmentRuns(ctx context.Context, orgID uuid.UUID) ([]models.LeadEnrichmentRun, error) { + return s.Repo.ActiveEnrichmentRuns(ctx, orgID) +} + +// RunPendingEnrichment picks up queued runs and runs a crashed process left behind. +func (s *Service) RunPendingEnrichment(ctx context.Context) error { + ids, err := s.Repo.DueEnrichmentRuns(ctx, 10) + if err != nil { + return err + } + for _, id := range ids { + if ctx.Err() != nil { + return ctx.Err() + } + s.runEnrichment(ctx, id) + } + return nil +} + +func (s *Service) runEnrichment(ctx context.Context, id uuid.UUID) { + run, err := s.Repo.ClaimEnrichmentRun(ctx, id) + if err != nil || run == nil { + if err != nil { + log.Warn().Err(err).Str("run", id.String()).Msg("leadfinder: could not claim enrichment run") + } + return + } + err = s.enrich(ctx, run) + run.Status = "done" + if err != nil { + run.Status = "error" + var xe *errx.Error + if errors.As(err, &xe) { + run.LastError = xe.Message + } else { + run.LastError = err.Error() + } + if !errors.Is(err, errOutOfCredits) { + log.Warn().Err(err).Str("run", id.String()).Msg("leadfinder: enrichment run failed") + } + } + fin, cancel := context.WithTimeout(context.WithoutCancel(ctx), 15*time.Second) + defer cancel() + if ferr := s.Repo.FinishEnrichmentRun(fin, run); ferr != nil { + log.Warn().Err(ferr).Str("run", id.String()).Msg("leadfinder: could not finish enrichment run") + } + if s.Audit != nil && run.RequestedByUserID != nil { + s.Audit.LogAction(fin, run.OrganizationID, *run.RequestedByUserID, models.AuditActionUpdate, models.AuditEntityLead, nil, "", "", + nil, map[string]string{"enrichment_run": run.ID.String(), "status": run.Status}) + } +} + +// enrich walks the run's leads from where it stopped, a chunk at a time. +func (s *Service) enrich(ctx context.Context, run *models.LeadEnrichmentRun) error { + for run.Processed < len(run.LeadIDs) { + if ctx.Err() != nil { + return ctx.Err() + } + end := min(run.Processed+enrichChunk, len(run.LeadIDs)) + leads, err := s.Repo.LeadsByIDs(ctx, run.OrganizationID, run.LeadIDs[run.Processed:end]) + if err != nil { + return err + } + var ( + mu sync.Mutex + wg sync.WaitGroup + stopErr error + ) + sem := make(chan struct{}, enrichParallel) + for i := range leads { + wg.Add(1) + sem <- struct{}{} + go func(l *models.Lead) { + defer wg.Done() + defer func() { <-sem }() + out, found, err := s.enrichLead(ctx, run, l) + mu.Lock() + defer mu.Unlock() + run.PeopleFound += found + switch { + case errors.Is(err, errOutOfCredits): + stopErr = err + case err != nil || out == outcomeFailed: + run.Failed++ + case out == outcomeNoWebsite: + run.NoWebsite++ + case out == outcomeCharged && s.metered(): + run.CreditsConsumed += credits.CostLeadEnrich + } + if err == nil && l.Email != "" { + run.EmailsFound++ + } + }(&leads[i]) + } + wg.Wait() + // A lead deleted since the run started counts as processed. + run.Processed = end + if err := s.Repo.UpdateEnrichmentProgress(ctx, run); err != nil { + return err + } + if stopErr != nil { + return stopErr + } + } + return nil +} + +type enrichOutcome int + +const ( + outcomeNoWebsite enrichOutcome = iota + outcomeCharged + outcomeFailed +) + +func (s *Service) enrichLead(ctx context.Context, run *models.LeadEnrichmentRun, l *models.Lead) (enrichOutcome, int, error) { + lctx, cancel := context.WithTimeout(ctx, enrichLeadTimeout) + defer cancel() + l.OrganizationID = run.OrganizationID + found := l.Site.FoundWebsite + if l.Website == "" { + l.Website, l.Domain = s.crawler.FindWebsite(lctx, l) + found = l.Website != "" + } + if l.Website == "" { + l.EnrichmentStatus = models.LeadEnrichmentNoWebsite + s.finishEmails(lctx, run, l, nil) + return outcomeNoWebsite, 0, s.Repo.SaveEnrichment(lctx, l) + } + key := "lead_enrich:" + run.ID.String() + ":" + l.ID.String() + if s.metered() { + if _, err := s.Credits.Charge(lctx, run.OrganizationID, credits.CostLeadEnrich, "lead_enrich", key); err != nil { + if errors.Is(err, credits.ErrInsufficientCredits) || errors.Is(err, credits.ErrCapExceeded) { + return outcomeFailed, 0, errOutOfCredits + } + return outcomeFailed, 0, err + } + } + res, err := s.crawler.Crawl(lctx, l.Website) + if err != nil { + now := time.Now() + res = &CrawlResult{Site: models.LeadSite{Error: err.Error(), CheckedAt: &now}} + } + // What earlier runs learned about the domain's addresses outlives this read. + prev := l.Site + l.Site = res.Site + if l.Site.EmailPattern == "" { + l.Site.EmailPattern = prev.EmailPattern + } + l.Site.AcceptsAll = prev.AcceptsAll + l.Site.FoundWebsite = found + outcome := outcomeCharged + if res.Site.Reachable { + l.EnrichmentStatus = models.LeadEnrichmentDone + } else { + // A site that never answered costs nothing. + l.EnrichmentStatus = models.LeadEnrichmentFailed + outcome = outcomeFailed + if s.metered() { + if _, rerr := s.Credits.RefundCharge(context.WithoutCancel(lctx), run.OrganizationID, key, "lead_enrich_refund"); rerr != nil { + log.Warn().Err(rerr).Msg("leadfinder: could not refund an unreachable site") + } + } + } + if l.Socials == nil { + l.Socials = map[string]string{} + } + for k, v := range res.Socials { + if l.Socials[k] == "" { + l.Socials[k] = v + } + } + if l.Phone == "" && len(res.Site.Phones) > 0 { + l.Phone = res.Site.Phones[0] + } + s.finishEmails(lctx, run, l, res.Emails) + people := 0 + if run.People && res.Site.Reachable { + n, err := s.enrichPeople(lctx, run, l, res.People) + if err != nil { + log.Warn().Err(err).Str("lead", l.ID.String()).Msg("leadfinder: could not save a lead's people") + } + people = n + } + return outcome, people, s.Repo.SaveEnrichment(lctx, l) +} + +// finishEmails merges found addresses into the lead, verifies the best few +// and picks the one to reach out to. A suppressed address is kept on the lead +// so nobody adds it again by hand, and is never the one picked. +func (s *Service) finishEmails(ctx context.Context, run *models.LeadEnrichmentRun, l *models.Lead, found []FoundEmail) { + byEmail := map[string]bool{} + var list []models.LeadEmail + for _, e := range l.Emails { + if e.Email != "" && !byEmail[e.Email] { + list = append(list, e) + byEmail[e.Email] = true + } + } + for _, f := range found { + if byEmail[f.Email] { + continue + } + list = append(list, models.LeadEmail{Email: f.Email, Source: "website", URL: f.URL, DomainMatch: emailDomainMatches(f.Email, l.Domain)}) + byEmail[f.Email] = true + } + if len(list) == 0 { + l.Emails, l.Email = []models.LeadEmail{}, "" + return + } + addrs := make([]string, 0, len(list)) + for _, e := range list { + addrs = append(addrs, e.Email) + } + suppressed, err := s.Repo.SuppressedEmails(ctx, run.OrganizationID, addrs) + if err != nil { + log.Warn().Err(err).Msg("leadfinder: could not check suppression") + suppressed = map[string]bool{} + for _, a := range addrs { + // Unknown means not usable: nothing is picked until the check works. + suppressed[a] = true + } + } + for i := range list { + if suppressed[list[i].Email] { + list[i].Status = "suppressed" + } else if list[i].Status == "suppressed" { + // No longer suppressed: verify it again like a new address. + list[i].Status, list[i].SubStatus = "", "" + } + } + sort.SliceStable(list, func(i, j int) bool { return emailRank(list[i]) < emailRank(list[j]) }) + if run.Verify && s.Verifier != nil { + checked := 0 + for i := range list { + if checked >= enrichVerifyMax { + break + } + if list[i].Status != "" { + continue + } + r := s.Verifier.VerifyAddress(ctx, run.OrganizationID, list[i].Email) + list[i].Status, list[i].SubStatus = string(r.Status), string(r.SubStatus) + checked++ + } + sort.SliceStable(list, func(i, j int) bool { return emailRank(list[i]) < emailRank(list[j]) }) + } + l.Emails = list + l.Email = "" + if top := list[0]; top.Status != "suppressed" && top.Status != string(emailverify.StatusInvalid) { + l.Email = top.Email + } +} + +// genericLocals read as a business's front desk, the right first contact. +var genericLocals = map[string]bool{"info": true, "hello": true, "contact": true, "office": true, "hi": true, "enquiries": true, "inquiries": true, "admin": true, "mail": true, "team": true} + +// emailRank orders addresses best first: deliverable, on the business's own +// domain, a front desk before a named person's address picked off a page. +func emailRank(e models.LeadEmail) int { + r := 0 + switch e.Status { + case string(emailverify.StatusValid): + case "", string(emailverify.StatusUnknown): + r += 20 + case string(emailverify.StatusRisky): + r += 30 + case string(emailverify.StatusInvalid): + r += 200 + case "suppressed": + r += 300 + } + if !e.DomainMatch { + r += 10 + } + local := e.Email + if at := strings.IndexByte(local, '@'); at >= 0 { + local = local[:at] + } + if strings.HasPrefix(local, "noreply") || strings.HasPrefix(local, "no-reply") || strings.HasPrefix(local, "donotreply") { + r += 100 + } else if !genericLocals[local] { + r += 2 + } + return r +} diff --git a/internal/app/leadfinder/export.go b/internal/app/leadfinder/export.go new file mode 100644 index 000000000..e76469499 --- /dev/null +++ b/internal/app/leadfinder/export.go @@ -0,0 +1,368 @@ +package leadfinder + +import ( + "context" + "encoding/csv" + "encoding/json" + "io" + "regexp" + "strconv" + "strings" + "time" + + "github.com/google/uuid" + "github.com/xuri/excelize/v2" + + "github.com/warmbly/warmbly/internal/errx" + "github.com/warmbly/warmbly/internal/models" +) + +// ExportColumn is one column a lead export can carry. +type ExportColumn struct { + Key string `json:"key"` + Label string `json:"label"` + value func(l *models.Lead) string +} + +func fmtFloat(v *float64) string { + if v == nil { + return "" + } + return strconv.FormatFloat(*v, 'f', -1, 64) +} + +func fmtInt(v *int) string { + if v == nil { + return "" + } + return strconv.Itoa(*v) +} + +func primaryEmail(l *models.Lead) *models.LeadEmail { + for i := range l.Emails { + if l.Emails[i].Email == l.Email { + return &l.Emails[i] + } + } + return nil +} + +func social(kind string) func(l *models.Lead) string { + return func(l *models.Lead) string { return l.Socials[kind] } +} + +// ExportColumns are every column, in file order. +var ExportColumns = []ExportColumn{ + {"name", "Name", func(l *models.Lead) string { return l.Name }}, + {"category", "Category", func(l *models.Lead) string { return l.Category }}, + {"email", "Email", func(l *models.Lead) string { return l.Email }}, + {"email_status", "Email status", func(l *models.Lead) string { + if e := primaryEmail(l); e != nil { + return e.Status + } + return "" + }}, + {"other_emails", "Other emails", func(l *models.Lead) string { + var out []string + for _, e := range l.Emails { + if e.Email != l.Email && e.Status != "suppressed" && e.Status != "invalid" { + out = append(out, e.Email) + } + } + return strings.Join(out, "; ") + }}, + {"phone", "Phone", func(l *models.Lead) string { return l.Phone }}, + {"website", "Website", func(l *models.Lead) string { return l.Website }}, + {"domain", "Domain", func(l *models.Lead) string { return l.Domain }}, + {"address", "Address", func(l *models.Lead) string { return l.Address }}, + {"street", "Street", func(l *models.Lead) string { return l.Street }}, + {"city", "City", func(l *models.Lead) string { return l.City }}, + {"region", "Region", func(l *models.Lead) string { return l.Region }}, + {"postcode", "Postcode", func(l *models.Lead) string { return l.Postcode }}, + {"country", "Country", func(l *models.Lead) string { return l.Country }}, + {"latitude", "Latitude", func(l *models.Lead) string { return strconv.FormatFloat(l.Latitude, 'f', 6, 64) }}, + {"longitude", "Longitude", func(l *models.Lead) string { return strconv.FormatFloat(l.Longitude, 'f', 6, 64) }}, + {"rating", "Rating", func(l *models.Lead) string { return fmtFloat(l.Rating) }}, + {"review_count", "Reviews", func(l *models.Lead) string { return fmtInt(l.ReviewCount) }}, + {"price_level", "Price level", func(l *models.Lead) string { return fmtInt(l.PriceLevel) }}, + {"business_status", "Business status", func(l *models.Lead) string { return l.BusinessStatus }}, + {"hours", "Hours", func(l *models.Lead) string { return strings.Join(l.Hours, "; ") }}, + {"facebook", "Facebook", social("facebook")}, + {"instagram", "Instagram", social("instagram")}, + {"linkedin", "LinkedIn", social("linkedin")}, + {"twitter", "X (Twitter)", social("twitter")}, + {"tiktok", "TikTok", social("tiktok")}, + {"youtube", "YouTube", social("youtube")}, + {"site_platform", "Website platform", func(l *models.Lead) string { return l.Site.Platform }}, + {"site_signals", "Website signals", func(l *models.Lead) string { return strings.Join(l.Site.Signals, "; ") }}, + {"chain", "Chain", func(l *models.Lead) string { return l.Chain }}, + {"score", "Score", func(l *models.Lead) string { return strconv.Itoa(l.Score) }}, + {"status", "Status", func(l *models.Lead) string { return string(l.Status) }}, + {"tags", "Tags", func(l *models.Lead) string { return strings.Join(l.Tags, "; ") }}, + {"notes", "Notes", func(l *models.Lead) string { return l.Notes }}, + {"maps_url", "Map link", func(l *models.Lead) string { return l.MapsURL }}, + {"people", "People", func(l *models.Lead) string { + out := make([]string, 0, len(l.People)) + for _, p := range l.People { + v := p.Name + if p.Title != "" { + v += " (" + p.Title + ")" + } + if p.Email != "" && p.EmailStatus != "suppressed" { + v += " <" + p.Email + ">" + } + out = append(out, v) + } + return strings.Join(out, "; ") + }}, + {"provider", "Source", func(l *models.Lead) string { return providerMeta[l.Provider].Name }}, + {"external_id", "Source id", func(l *models.Lead) string { return l.ExternalID }}, + {"first_seen_at", "First seen", func(l *models.Lead) string { return l.FirstSeenAt.UTC().Format(time.RFC3339) }}, +} + +// PersonColumn is one column a one-row-per-person export leads with. +type PersonColumn struct { + Key string `json:"key"` + Label string `json:"label"` + value func(p *models.LeadPerson) string +} + +// PersonColumns lead every row of a one-row-per-person export, in file order. +var PersonColumns = []PersonColumn{ + {"person_name", "Person", func(p *models.LeadPerson) string { return p.Name }}, + {"person_first_name", "First name", func(p *models.LeadPerson) string { return p.FirstName }}, + {"person_last_name", "Last name", func(p *models.LeadPerson) string { return p.LastName }}, + {"person_title", "Title", func(p *models.LeadPerson) string { return p.Title }}, + {"person_seniority", "Seniority", func(p *models.LeadPerson) string { return string(p.Seniority) }}, + {"person_email", "Person email", func(p *models.LeadPerson) string { + if p.EmailStatus == "suppressed" { + return "" + } + return p.Email + }}, + {"person_email_status", "Person email status", func(p *models.LeadPerson) string { return p.EmailStatus }}, + {"person_email_confidence", "Person email confidence", func(p *models.LeadPerson) string { + if p.Email == "" { + return "" + } + return strconv.Itoa(p.EmailConfidence) + }}, + {"person_linkedin", "Person LinkedIn", func(p *models.LeadPerson) string { return p.LinkedInURL }}, + {"person_phone", "Person phone", func(p *models.LeadPerson) string { return p.Phone }}, + {"person_source", "Found on", func(p *models.LeadPerson) string { return p.SourceURL }}, +} + +// DefaultExportColumns is what an export carries when none are picked. +var DefaultExportColumns = []string{ + "name", "category", "email", "email_status", "other_emails", "phone", "website", "address", "city", "region", + "postcode", "country", "rating", "review_count", "facebook", "instagram", "linkedin", "site_platform", + "site_signals", "score", "status", "tags", "maps_url", +} + +// ExportRequest asks for a file of leads. +type ExportRequest struct { + models.LeadSelection + Format string `json:"format"` + Columns []string `json:"columns"` + // Rows is "leads" (one row per business, the default) or "people" (one row + // per person, with the business's columns repeated on each). + Rows string `json:"rows"` +} + +// Export writes the selected leads to w and returns the content type and filename. +func (s *Service) Export(ctx context.Context, orgID uuid.UUID, req *ExportRequest, w io.Writer) (string, string, error) { + format := strings.ToLower(strings.TrimSpace(req.Format)) + if format == "" { + format = "csv" + } + if format != "csv" && format != "xlsx" && format != "json" { + return "", "", errx.New(errx.BadRequest, "format must be csv, xlsx or json") + } + keys := req.Columns + if len(keys) == 0 { + keys = DefaultExportColumns + } + cols := make([]ExportColumn, 0, len(keys)) + for _, k := range keys { + c := columnByKey(k) + if c == nil { + return "", "", errx.New(errx.BadRequest, "unknown export column: "+k) + } + cols = append(cols, *c) + } + rows := strings.ToLower(strings.TrimSpace(req.Rows)) + if rows == "" { + rows = "leads" + } + if rows != "leads" && rows != "people" { + return "", "", errx.New(errx.BadRequest, "rows must be leads or people") + } + ids, err := s.Resolve(ctx, orgID, &req.LeadSelection) + if err != nil { + return "", "", err + } + needPeople := rows == "people" + for _, k := range keys { + needPeople = needPeople || k == "people" + } + leads := make([]models.Lead, 0, len(ids)) + for start := 0; start < len(ids); start += 500 { + batch, err := s.Repo.LeadsByIDs(ctx, orgID, ids[start:min(start+500, len(ids))]) + if err != nil { + return "", "", err + } + if needPeople { + people, err := s.Repo.PeopleForLeads(ctx, orgID, ids[start:min(start+500, len(ids))]) + if err != nil { + return "", "", err + } + for i := range batch { + batch[i].People = people[batch[i].ID] + } + } + leads = append(leads, batch...) + } + + var t exportTable + if rows == "people" { + for _, c := range PersonColumns { + t.keys, t.header = append(t.keys, c.Key), append(t.header, c.Label) + } + } + for _, c := range cols { + t.keys, t.header = append(t.keys, c.Key), append(t.header, c.Label) + } + for i := range leads { + l := &leads[i] + lead := make([]string, len(cols)) + for j, c := range cols { + lead[j] = c.value(l) + } + if rows == "leads" { + t.rows = append(t.rows, lead) + continue + } + for k := range l.People { + row := make([]string, 0, len(PersonColumns)+len(cols)) + for _, c := range PersonColumns { + row = append(row, c.value(&l.People[k])) + } + t.rows = append(t.rows, append(row, lead...)) + } + } + + base := "leads-" + if rows == "people" { + base = "lead-people-" + } + name := base + time.Now().UTC().Format("2006-01-02") + "." + format + switch format { + case "json": + out := make([]map[string]string, len(t.rows)) + for i, r := range t.rows { + row := make(map[string]string, len(t.keys)) + for j, k := range t.keys { + row[k] = r[j] + } + out[i] = row + } + return "application/json", name, json.NewEncoder(w).Encode(out) + case "xlsx": + return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", name, writeXLSX(w, &t) + } + cw := csv.NewWriter(w) + if err := cw.Write(t.header); err != nil { + return "", "", err + } + for _, r := range t.rows { + row := make([]string, len(r)) + for j, v := range r { + row[j] = cellSafe(v) + } + if err := cw.Write(row); err != nil { + return "", "", err + } + } + cw.Flush() + return "text/csv; charset=utf-8", name, cw.Error() +} + +// exportTable is an export laid out as cells, whatever the file format. +type exportTable struct { + keys []string + header []string + rows [][]string +} + +func columnByKey(k string) *ExportColumn { + for i := range ExportColumns { + if ExportColumns[i].Key == k { + return &ExportColumns[i] + } + } + return nil +} + +// phoneShape is a value that is only a phone number, which no spreadsheet runs. +var phoneShape = regexp.MustCompile(`^\+[0-9 ().\-/]+$`) + +// cellSafe keeps a provider's text from running as a spreadsheet formula. +func cellSafe(v string) string { + if v == "" || !strings.ContainsRune("=+-@\t\r\n", rune(v[0])) || phoneShape.MatchString(v) { + return v + } + if _, err := strconv.ParseFloat(v, 64); err == nil { + return v + } + return "'" + v +} + +func writeXLSX(w io.Writer, t *exportTable) error { + f := excelize.NewFile() + defer f.Close() + sheet := "Leads" + if err := f.SetSheetName("Sheet1", sheet); err != nil { + return err + } + sw, err := f.NewStreamWriter(sheet) + if err != nil { + return err + } + bold, _ := f.NewStyle(&excelize.Style{ + Font: &excelize.Font{Bold: true}, + Fill: excelize.Fill{Type: "pattern", Pattern: 1, Color: []string{"#F1F5F9"}}, + }) + _ = sw.SetColWidth(1, len(t.keys), 22) + if err := sw.SetPanes(&excelize.Panes{Freeze: true, YSplit: 1, TopLeftCell: "A2", ActivePane: "bottomLeft"}); err != nil { + return err + } + header := make([]any, len(t.header)) + for i, h := range t.header { + header[i] = excelize.Cell{StyleID: bold, Value: h} + } + if err := sw.SetRow("A1", header); err != nil { + return err + } + numeric := map[string]bool{"latitude": true, "longitude": true, "rating": true, "review_count": true, "price_level": true, "score": true, "person_email_confidence": true} + for r, cells := range t.rows { + row := make([]any, len(cells)) + for i, v := range cells { + if numeric[t.keys[i]] && v != "" { + if n, err := strconv.ParseFloat(v, 64); err == nil { + row[i] = n + continue + } + } + // Excel stores these as text, never formulas, so they are written as they are. + row[i] = v + } + cell, _ := excelize.CoordinatesToCellName(1, r+2) + if err := sw.SetRow(cell, row); err != nil { + return err + } + } + if err := sw.Flush(); err != nil { + return err + } + return f.Write(w) +} diff --git a/internal/app/leadfinder/foursquare.go b/internal/app/leadfinder/foursquare.go new file mode 100644 index 000000000..e9fe56fc4 --- /dev/null +++ b/internal/app/leadfinder/foursquare.go @@ -0,0 +1,216 @@ +package leadfinder + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "regexp" + "strings" + + "github.com/warmbly/warmbly/internal/models" +) + +const ( + foursquareSearchURL = "https://places-api.foursquare.com/places/search" + foursquareVersion = "2025-06-17" + foursquareFields = "fsq_place_id,name,latitude,longitude,location,categories,chains,tel,website,email," + + "social_media,rating,stats,price,hours,description,date_closed" +) + +type foursquareProvider struct { + key string +} + +// NewFoursquare builds the Foursquare Places provider with a service key. +func NewFoursquare(key string) Provider { + return &foursquareProvider{key: key} +} + +func (p *foursquareProvider) ID() models.LeadProvider { return models.LeadProviderFoursquare } + +type foursquarePlace struct { + ID string `json:"fsq_place_id"` + Name string `json:"name"` + Latitude float64 `json:"latitude"` + Longitude float64 `json:"longitude"` + Location struct { + Address string `json:"address"` + Locality string `json:"locality"` + Region string `json:"region"` + Postcode string `json:"postcode"` + Country string `json:"country"` + FormattedAddress string `json:"formatted_address"` + } `json:"location"` + Categories []struct { + Name string `json:"name"` + } `json:"categories"` + Chains []struct { + Name string `json:"name"` + } `json:"chains"` + Tel string `json:"tel"` + Website string `json:"website"` + Email string `json:"email"` + SocialMedia struct { + FacebookID string `json:"facebook_id"` + Instagram string `json:"instagram"` + Twitter string `json:"twitter"` + } `json:"social_media"` + Rating *float64 `json:"rating"` + Stats struct { + TotalRatings *int `json:"total_ratings"` + } `json:"stats"` + Price *int `json:"price"` + Hours struct { + Display string `json:"display"` + } `json:"hours"` + Description string `json:"description"` + DateClosed string `json:"date_closed"` +} + +var linkNext = regexp.MustCompile(`<([^>]+)>;\s*rel="next"`) + +func (p *foursquareProvider) Search(ctx context.Context, q Query) (*Page, error) { + text := strings.TrimSpace(q.Text) + if q.Category != nil { + text = strings.TrimSpace(text + " " + q.Category.Term) + } + if text == "" { + return nil, errors.New("pick a category or type what to look for") + } + target := q.Cursor + if target == "" { + b := q.Area.Bounds + v := url.Values{ + "query": {text}, + "ne": {fmt.Sprintf("%.6f,%.6f", b.North, b.East)}, + "sw": {fmt.Sprintf("%.6f,%.6f", b.South, b.West)}, + "limit": {"50"}, + "fields": {foursquareFields}, + } + target = foursquareSearchURL + "?" + v.Encode() + } else if u, err := url.Parse(target); err != nil || u.Host != "places-api.foursquare.com" { + return nil, errors.New("the next page of this search is no longer available") + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, target, nil) + if err != nil { + return nil, err + } + req.Header.Set("Authorization", "Bearer "+p.key) + req.Header.Set("X-Places-Api-Version", foursquareVersion) + req.Header.Set("Accept", "application/json") + if q.Language != "" { + req.Header.Set("Accept-Language", q.Language) + } + resp, err := providerHTTP.Do(req) + if err != nil { + return nil, errors.New("Foursquare did not answer; try again") + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return nil, statusErr(resp.StatusCode) + } + var body struct { + Results []foursquarePlace `json:"results"` + } + if err := json.NewDecoder(io.LimitReader(resp.Body, 8<<20)).Decode(&body); err != nil { + return nil, errors.New("Foursquare sent an answer that could not be read") + } + out := make([]models.Lead, 0, len(body.Results)) + for _, pl := range body.Results { + out = append(out, foursquareLead(pl)) + } + next := "" + if m := linkNext.FindStringSubmatch(resp.Header.Get("Link")); m != nil && len(body.Results) > 0 { + next = m[1] + } + return &Page{Leads: out, NextCursor: next}, nil +} + +func foursquareLead(pl foursquarePlace) models.Lead { + l := models.Lead{ + Provider: models.LeadProviderFoursquare, + ExternalID: pl.ID, + Name: pl.Name, + Latitude: pl.Latitude, + Longitude: pl.Longitude, + Street: pl.Location.Address, + City: pl.Location.Locality, + Region: pl.Location.Region, + Postcode: pl.Location.Postcode, + Country: pl.Location.Country, + Address: pl.Location.FormattedAddress, + Phone: pl.Tel, + ReviewCount: pl.Stats.TotalRatings, + PriceLevel: pl.Price, + Description: pl.Description, + MapsURL: "https://foursquare.com/v/" + pl.ID, + Socials: map[string]string{}, + Emails: []models.LeadEmail{}, + Hours: []string{}, + } + if l.Address == "" { + l.Address = joinAddress(l.Street, l.City, strings.TrimSpace(l.Region+" "+l.Postcode), l.Country) + } + for _, c := range pl.Categories { + l.Categories = append(l.Categories, c.Name) + } + if len(l.Categories) > 0 { + l.Category = l.Categories[0] + } + if len(pl.Chains) > 0 { + l.Chain = pl.Chains[0].Name + } + if pl.Rating != nil { + // Foursquare rates out of ten; the finder shows stars out of five. + r := *pl.Rating / 2 + l.Rating = &r + } + l.Website, l.Domain = NormalizeWebsite(pl.Website) + if e := cleanEmail(pl.Email); e != "" { + l.Email = e + l.Emails = []models.LeadEmail{{Email: e, Source: string(models.LeadProviderFoursquare), DomainMatch: emailDomainMatches(e, l.Domain)}} + } + if pl.SocialMedia.FacebookID != "" { + l.Socials["facebook"] = "https://www.facebook.com/" + pl.SocialMedia.FacebookID + } + if u := socialURL("instagram", pl.SocialMedia.Instagram); u != "" { + l.Socials["instagram"] = u + } + if u := socialURL("twitter", pl.SocialMedia.Twitter); u != "" { + l.Socials["twitter"] = u + } + if pl.Hours.Display != "" { + for _, part := range strings.Split(pl.Hours.Display, ";") { + if part = strings.TrimSpace(part); part != "" { + l.Hours = append(l.Hours, part) + } + } + } + if pl.DateClosed != "" { + l.BusinessStatus = "closed" + } + return l +} + +// CheckFoursquareKey runs one tiny search to prove the key can call Places. +func CheckFoursquareKey(ctx context.Context, key string) error { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, foursquareSearchURL+"?query=coffee&limit=1&fields=fsq_place_id&ll=40.7484,-73.9857", nil) + if err != nil { + return err + } + req.Header.Set("Authorization", "Bearer "+key) + req.Header.Set("X-Places-Api-Version", foursquareVersion) + resp, err := providerHTTP.Do(req) + if err != nil { + return errors.New("Foursquare did not answer; try again") + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return statusErr(resp.StatusCode) + } + return nil +} diff --git a/internal/app/leadfinder/geo.go b/internal/app/leadfinder/geo.go new file mode 100644 index 000000000..ec9ecadf0 --- /dev/null +++ b/internal/app/leadfinder/geo.go @@ -0,0 +1,140 @@ +package leadfinder + +import ( + "errors" + "math" + + "github.com/warmbly/warmbly/internal/models" +) + +const ( + earthRadiusM = 6371000.0 + // maxPolygonPoints bounds a drawn shape. + maxPolygonPoints = 200 + // maxRadiusM is the widest circle any provider is asked about. + maxRadiusM = 50000 +) + +// NormalizeArea validates a requested area and fills in its bounding box. +func NormalizeArea(a models.LeadArea) (models.LeadArea, error) { + switch a.Kind { + case models.LeadAreaCircle: + if a.Center == nil || !validPoint(*a.Center) { + return a, errors.New("a circle needs a center on the map") + } + if a.RadiusM < 50 || a.RadiusM > maxRadiusM { + return a, errors.New("a circle's radius must be between 50 m and 50 km") + } + dLat := a.RadiusM / earthRadiusM * 180 / math.Pi + dLng := dLat / math.Max(math.Cos(a.Center.Lat*math.Pi/180), 0.01) + a.Bounds = models.LeadBounds{ + South: clampLat(a.Center.Lat - dLat), North: clampLat(a.Center.Lat + dLat), + West: wrapLng(a.Center.Lng - dLng), East: wrapLng(a.Center.Lng + dLng), + } + a.Polygon = nil + case models.LeadAreaPolygon: + if len(a.Polygon) < 3 || len(a.Polygon) > maxPolygonPoints { + return a, errors.New("a drawn area needs between 3 and 200 points") + } + b := models.LeadBounds{South: 90, North: -90, West: 180, East: -180} + for _, p := range a.Polygon { + if !validPoint(p) { + return a, errors.New("a drawn area has a point off the map") + } + b.South, b.North = math.Min(b.South, p.Lat), math.Max(b.North, p.Lat) + b.West, b.East = math.Min(b.West, p.Lng), math.Max(b.East, p.Lng) + } + a.Bounds = b + a.Center, a.RadiusM = nil, 0 + default: + a.Kind = models.LeadAreaBBox + b := a.Bounds + if b.South >= b.North || b.South < -90 || b.North > 90 || b.West < -180 || b.West > 180 || b.East < -180 || b.East > 180 { + return a, errors.New("the map area is not a valid rectangle") + } + a.Center, a.RadiusM, a.Polygon = nil, 0, nil + } + return a, nil +} + +func validPoint(p models.LatLng) bool { + return p.Lat >= -90 && p.Lat <= 90 && p.Lng >= -180 && p.Lng <= 180 +} + +func clampLat(v float64) float64 { return math.Max(-89.9, math.Min(89.9, v)) } + +func wrapLng(v float64) float64 { + for v > 180 { + v -= 360 + } + for v < -180 { + v += 360 + } + return v +} + +// lngSpan is the bounds' width in degrees, across the antimeridian when needed. +func lngSpan(b models.LeadBounds) float64 { + if b.West <= b.East { + return b.East - b.West + } + return 360 - b.West + b.East +} + +// Center is the middle of the bounds. +func Center(b models.LeadBounds) models.LatLng { + return models.LatLng{Lat: (b.South + b.North) / 2, Lng: wrapLng(b.West + lngSpan(b)/2)} +} + +// DiagonalM is the distance across the bounds, corner to corner. +func DiagonalM(b models.LeadBounds) float64 { + return Distance(models.LatLng{Lat: b.South, Lng: b.West}, models.LatLng{Lat: b.North, Lng: b.West + lngSpan(b)}) +} + +// AreaKM2 approximates the bounds' surface. +func AreaKM2(b models.LeadBounds) float64 { + midLat := (b.South + b.North) / 2 * math.Pi / 180 + h := (b.North - b.South) * math.Pi / 180 * earthRadiusM + w := lngSpan(b) * math.Pi / 180 * earthRadiusM * math.Cos(midLat) + return h * w / 1e6 +} + +// Distance is the great-circle distance between two points in meters. +func Distance(a, b models.LatLng) float64 { + la1, la2 := a.Lat*math.Pi/180, b.Lat*math.Pi/180 + dLat := la2 - la1 + dLng := (b.Lng - a.Lng) * math.Pi / 180 + h := math.Sin(dLat/2)*math.Sin(dLat/2) + math.Cos(la1)*math.Cos(la2)*math.Sin(dLng/2)*math.Sin(dLng/2) + return 2 * earthRadiusM * math.Asin(math.Min(1, math.Sqrt(h))) +} + +// Contains reports whether a point is inside the area. +func Contains(a models.LeadArea, p models.LatLng) bool { + switch a.Kind { + case models.LeadAreaCircle: + return a.Center != nil && Distance(*a.Center, p) <= a.RadiusM + case models.LeadAreaPolygon: + return inPolygon(a.Polygon, p) + } + b := a.Bounds + if p.Lat < b.South || p.Lat > b.North { + return false + } + if b.West <= b.East { + return p.Lng >= b.West && p.Lng <= b.East + } + return p.Lng >= b.West || p.Lng <= b.East +} + +// inPolygon is the even-odd ray cast. +func inPolygon(poly []models.LatLng, p models.LatLng) bool { + in := false + for i, j := 0, len(poly)-1; i < len(poly); j, i = i, i+1 { + a, b := poly[i], poly[j] + if (a.Lat > p.Lat) != (b.Lat > p.Lat) && + p.Lng < (b.Lng-a.Lng)*(p.Lat-a.Lat)/(b.Lat-a.Lat)+a.Lng { + in = !in + } + } + return in +} diff --git a/internal/app/leadfinder/geocode.go b/internal/app/leadfinder/geocode.go new file mode 100644 index 000000000..c9448f759 --- /dev/null +++ b/internal/app/leadfinder/geocode.go @@ -0,0 +1,146 @@ +package leadfinder + +import ( + "context" + "encoding/json" + "errors" + "io" + "net/http" + "net/url" + "sort" + "strconv" + "strings" + + "github.com/warmbly/warmbly/internal/models" +) + +// DefaultGeocoderURL is Komoot's public Photon instance; operators can point +// LEAD_FINDER_GEOCODER_URL at their own. +const DefaultGeocoderURL = "https://photon.komoot.io/api" + +// GeocodeResult is one place a location search matched. +type GeocodeResult struct { + Label string `json:"label"` + Detail string `json:"detail"` + Kind string `json:"kind"` + Center models.LatLng `json:"center"` + Bounds *models.LeadBounds `json:"bounds,omitempty"` +} + +// Geocoder turns a typed location into points on the map. +type Geocoder struct { + endpoint string + userAgent string +} + +// NewGeocoder builds a Photon-compatible geocoder. +func NewGeocoder(endpoint, userAgent string) *Geocoder { + if endpoint == "" { + endpoint = DefaultGeocoderURL + } + return &Geocoder{endpoint: endpoint, userAgent: userAgent} +} + +// Search returns up to limit places matching q, nearest bias first when given. +func (g *Geocoder) Search(ctx context.Context, q string, near *models.LatLng, limit int, lang string) ([]GeocodeResult, error) { + q = strings.TrimSpace(q) + if q == "" { + return []GeocodeResult{}, nil + } + v := url.Values{"q": {q}, "limit": {strconv.Itoa(limit)}} + if near != nil { + v.Set("lat", strconv.FormatFloat(near.Lat, 'f', 5, 64)) + v.Set("lon", strconv.FormatFloat(near.Lng, 'f', 5, 64)) + } + if lang = strings.ToLower(strings.TrimSpace(lang)); lang == "en" || lang == "de" || lang == "fr" { + v.Set("lang", lang) + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, g.endpoint+"?"+v.Encode(), nil) + if err != nil { + return nil, err + } + req.Header.Set("User-Agent", g.userAgent) + resp, err := providerHTTP.Do(req) + if err != nil { + return nil, errors.New("the location search did not answer; try again") + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return nil, statusErr(resp.StatusCode) + } + var body struct { + Features []struct { + Geometry struct { + Coordinates []float64 `json:"coordinates"` + } `json:"geometry"` + Properties struct { + Name string `json:"name"` + Street string `json:"street"` + HouseNumber string `json:"housenumber"` + City string `json:"city"` + County string `json:"county"` + State string `json:"state"` + Country string `json:"country"` + Postcode string `json:"postcode"` + Type string `json:"type"` + OSMValue string `json:"osm_value"` + Extent []float64 `json:"extent"` + } `json:"properties"` + } `json:"features"` + } + if err := json.NewDecoder(io.LimitReader(resp.Body, 2<<20)).Decode(&body); err != nil { + return nil, errors.New("the location search sent an answer that could not be read") + } + out := make([]GeocodeResult, 0, len(body.Features)) + seen := map[string]bool{} + for _, f := range body.Features { + if len(f.Geometry.Coordinates) < 2 { + continue + } + p := f.Properties + label := firstNonEmpty(p.Name, strings.TrimSpace(p.HouseNumber+" "+p.Street), p.City) + if label == "" { + continue + } + detailParts := []string{} + for _, part := range []string{p.City, p.State, p.Country} { + if part != "" && part != label { + detailParts = append(detailParts, part) + } + } + r := GeocodeResult{ + Label: label, + Detail: strings.Join(detailParts, ", "), + Kind: firstNonEmpty(p.Type, p.OSMValue), + Center: models.LatLng{Lat: f.Geometry.Coordinates[1], Lng: f.Geometry.Coordinates[0]}, + } + if len(p.Extent) == 4 { + r.Bounds = &models.LeadBounds{West: p.Extent[0], North: p.Extent[1], East: p.Extent[2], South: p.Extent[3]} + } + key := r.Label + "|" + r.Detail + if seen[key] { + continue + } + seen[key] = true + out = append(out, r) + } + // Someone picking where to search means a place far more often than a street. + sort.SliceStable(out, func(i, j int) bool { return placeRank(out[i].Kind) < placeRank(out[j].Kind) }) + return out, nil +} + +func placeRank(kind string) int { + switch kind { + case "city", "town", "village": + return 0 + case "district", "locality", "suburb", "neighbourhood": + return 1 + case "county", "state", "country", "region": + return 2 + case "street": + return 4 + case "house": + return 5 + } + return 3 +} diff --git a/internal/app/leadfinder/google.go b/internal/app/leadfinder/google.go new file mode 100644 index 000000000..2ddaa3558 --- /dev/null +++ b/internal/app/leadfinder/google.go @@ -0,0 +1,230 @@ +package leadfinder + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "net/http" + "strings" + + "github.com/warmbly/warmbly/internal/models" +) + +const googleSearchURL = "https://places.googleapis.com/v1/places:searchText" + +// googleFieldMask asks for what a lead shows and nothing billed beyond it. +const googleFieldMask = "places.id,places.displayName,places.formattedAddress,places.addressComponents," + + "places.location,places.types,places.primaryType,places.primaryTypeDisplayName,places.businessStatus," + + "places.googleMapsUri,places.nationalPhoneNumber,places.internationalPhoneNumber,places.websiteUri," + + "places.rating,places.userRatingCount,places.priceLevel,places.regularOpeningHours,places.editorialSummary,nextPageToken" + +type googleProvider struct { + key string + endpoint string +} + +// NewGooglePlaces builds the Google Places (New) provider with an API key. +func NewGooglePlaces(key string) Provider { + return &googleProvider{key: key, endpoint: googleSearchURL} +} + +func (p *googleProvider) ID() models.LeadProvider { return models.LeadProviderGooglePlaces } + +type googleText struct { + Text string `json:"text"` +} + +type googlePlace struct { + ID string `json:"id"` + DisplayName googleText `json:"displayName"` + FormattedAddress string `json:"formattedAddress"` + AddressComponents []struct { + LongText string `json:"longText"` + ShortText string `json:"shortText"` + Types []string `json:"types"` + } `json:"addressComponents"` + Location struct { + Latitude float64 `json:"latitude"` + Longitude float64 `json:"longitude"` + } `json:"location"` + Types []string `json:"types"` + PrimaryType string `json:"primaryType"` + PrimaryTypeDisplayName googleText `json:"primaryTypeDisplayName"` + BusinessStatus string `json:"businessStatus"` + GoogleMapsURI string `json:"googleMapsUri"` + NationalPhone string `json:"nationalPhoneNumber"` + InternationalPhone string `json:"internationalPhoneNumber"` + WebsiteURI string `json:"websiteUri"` + Rating *float64 `json:"rating"` + UserRatingCount *int `json:"userRatingCount"` + PriceLevel string `json:"priceLevel"` + RegularOpeningHours *struct { + WeekdayDescriptions []string `json:"weekdayDescriptions"` + } `json:"regularOpeningHours"` + EditorialSummary googleText `json:"editorialSummary"` +} + +func googleBody(q Query, withType bool) map[string]any { + text := strings.TrimSpace(q.Text) + if q.Category != nil { + text = strings.TrimSpace(text + " " + q.Category.Term) + } + b := q.Area.Bounds + body := map[string]any{ + "textQuery": text, + "pageSize": 20, + "locationRestriction": map[string]any{"rectangle": map[string]any{ + "low": map[string]float64{"latitude": b.South, "longitude": b.West}, + "high": map[string]float64{"latitude": b.North, "longitude": b.East}, + }}, + } + if withType && q.Category != nil && q.Category.GoogleType != "" { + body["includedType"] = q.Category.GoogleType + body["strictTypeFiltering"] = true + } + if q.Language != "" { + body["languageCode"] = q.Language + } + if q.Cursor != "" { + body["pageToken"] = q.Cursor + } + return body +} + +func (p *googleProvider) post(ctx context.Context, body map[string]any) ([]googlePlace, string, int, error) { + raw, _ := json.Marshal(body) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, p.endpoint, bytes.NewReader(raw)) + if err != nil { + return nil, "", 0, err + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-Goog-Api-Key", p.key) + req.Header.Set("X-Goog-FieldMask", googleFieldMask) + resp, err := providerHTTP.Do(req) + if err != nil { + return nil, "", 0, errors.New("Google Places did not answer; try again") + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + var e struct { + Error struct { + Message string `json:"message"` + Status string `json:"status"` + } `json:"error"` + } + _ = json.NewDecoder(io.LimitReader(resp.Body, 64<<10)).Decode(&e) + if resp.StatusCode == http.StatusBadRequest && strings.Contains(strings.ToLower(e.Error.Message), "api key") { + return nil, "", resp.StatusCode, ErrProviderKey + } + if resp.StatusCode == http.StatusBadRequest { + return nil, "", resp.StatusCode, errors.New("Google Places refused the search: " + e.Error.Message) + } + return nil, "", resp.StatusCode, statusErr(resp.StatusCode) + } + var out struct { + Places []googlePlace `json:"places"` + NextPageToken string `json:"nextPageToken"` + } + if err := json.NewDecoder(io.LimitReader(resp.Body, 8<<20)).Decode(&out); err != nil { + return nil, "", resp.StatusCode, errors.New("Google Places sent an answer that could not be read") + } + return out.Places, out.NextPageToken, resp.StatusCode, nil +} + +func (p *googleProvider) Search(ctx context.Context, q Query) (*Page, error) { + if strings.TrimSpace(q.Text) == "" && q.Category == nil { + return nil, errors.New("pick a category or type what to look for") + } + if q.Area.Bounds.West > q.Area.Bounds.East { + return nil, errors.New("Google Places cannot search across the date line; move the map") + } + places, next, code, err := p.post(ctx, googleBody(q, true)) + if err != nil && code == http.StatusBadRequest && !errors.Is(err, ErrProviderKey) && q.Category != nil && q.Category.GoogleType != "" { + // A type Google no longer knows falls back to the plain phrase. + places, next, _, err = p.post(ctx, googleBody(q, false)) + } + if err != nil { + return nil, err + } + out := make([]models.Lead, 0, len(places)) + for _, pl := range places { + out = append(out, googleLead(pl)) + } + return &Page{Leads: out, NextCursor: next}, nil +} + +func googleLead(pl googlePlace) models.Lead { + l := models.Lead{ + Provider: models.LeadProviderGooglePlaces, + ExternalID: pl.ID, + Name: pl.DisplayName.Text, + Address: pl.FormattedAddress, + Latitude: pl.Location.Latitude, + Longitude: pl.Location.Longitude, + Phone: firstNonEmpty(pl.InternationalPhone, pl.NationalPhone), + Rating: pl.Rating, + ReviewCount: pl.UserRatingCount, + MapsURL: pl.GoogleMapsURI, + Description: pl.EditorialSummary.Text, + Socials: map[string]string{}, + Emails: []models.LeadEmail{}, + Hours: []string{}, + } + l.Website, l.Domain = NormalizeWebsite(pl.WebsiteURI) + l.Category = firstNonEmpty(pl.PrimaryTypeDisplayName.Text, Humanize(pl.PrimaryType)) + for _, t := range pl.Types { + if t != "point_of_interest" && t != "establishment" { + l.Categories = append(l.Categories, Humanize(t)) + } + } + var number, route string + for _, c := range pl.AddressComponents { + for _, t := range c.Types { + switch t { + case "street_number": + number = c.LongText + case "route": + route = c.LongText + case "locality", "postal_town": + if l.City == "" { + l.City = c.LongText + } + case "administrative_area_level_1": + l.Region = c.ShortText + case "postal_code": + l.Postcode = c.LongText + case "country": + l.Country = c.ShortText + } + } + } + l.Street = strings.TrimSpace(number + " " + route) + switch pl.BusinessStatus { + case "CLOSED_PERMANENTLY": + l.BusinessStatus = "closed" + case "CLOSED_TEMPORARILY": + l.BusinessStatus = "temporarily_closed" + case "OPERATIONAL": + l.BusinessStatus = "operational" + } + if lvl := googlePriceLevels[pl.PriceLevel]; lvl > 0 { + l.PriceLevel = &lvl + } + if pl.RegularOpeningHours != nil { + l.Hours = append(l.Hours, pl.RegularOpeningHours.WeekdayDescriptions...) + } + return l +} + +var googlePriceLevels = map[string]int{ + "PRICE_LEVEL_INEXPENSIVE": 1, "PRICE_LEVEL_MODERATE": 2, "PRICE_LEVEL_EXPENSIVE": 3, "PRICE_LEVEL_VERY_EXPENSIVE": 4, +} + +// CheckGoogleKey runs one tiny search to prove the key can call Places (New). +func CheckGoogleKey(ctx context.Context, key string) error { + p := &googleProvider{key: key, endpoint: googleSearchURL} + _, _, _, err := p.post(ctx, map[string]any{"textQuery": "coffee", "pageSize": 1}) + return err +} diff --git a/internal/app/leadfinder/keys.go b/internal/app/leadfinder/keys.go new file mode 100644 index 000000000..9c7112a40 --- /dev/null +++ b/internal/app/leadfinder/keys.go @@ -0,0 +1,42 @@ +package leadfinder + +import ( + "context" + "errors" + "strings" + + "github.com/warmbly/warmbly/internal/app/integration" + "github.com/warmbly/warmbly/internal/models" +) + +// KeyCheckRegistry is where Connect looks up the check for a pasted key. +type KeyCheckRegistry interface { + SetCredentialCheck(provider models.IntegrationProvider, check integration.CredentialCheck) +} + +// RegisterKeyChecks makes Connect prove a provider key works before saving it. +func RegisterKeyChecks(reg KeyCheckRegistry) { + if reg == nil { + return + } + check := func(name string, probe func(ctx context.Context, key string) error) integration.CredentialCheck { + return func(ctx context.Context, config map[string]any) (map[string]any, error) { + key, _ := config["api_key"].(string) + key = strings.TrimSpace(key) + if key == "" { + return nil, errors.New("paste your " + name + " API key") + } + config["api_key"] = key + if err := probe(ctx, key); err != nil { + if errors.Is(err, ErrProviderKey) { + return nil, errors.New(name + " refused this key") + } + return nil, err + } + return map[string]any{}, nil + } + } + reg.SetCredentialCheck(models.IntegrationGooglePlaces, check("Google Places", CheckGoogleKey)) + reg.SetCredentialCheck(models.IntegrationFoursquare, check("Foursquare", CheckFoursquareKey)) + reg.SetCredentialCheck(models.IntegrationOutscraper, check("Outscraper", CheckOutscraperKey)) +} diff --git a/internal/app/leadfinder/leadfinder_test.go b/internal/app/leadfinder/leadfinder_test.go new file mode 100644 index 000000000..f63b5bfed --- /dev/null +++ b/internal/app/leadfinder/leadfinder_test.go @@ -0,0 +1,234 @@ +package leadfinder + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + "time" + + "github.com/warmbly/warmbly/internal/models" +) + +func TestParsePageFindsAddressesTheWayTheyArePublished(t *testing.T) { + src := `Bright Smiles Dental + + + + Email us +

Billing: billing [at] brightsmiles [dot] com

+ [email protected] + +

Sentry: 9f8e7d6c5b4a39281706f5e4d3c2b1a0@sentry.io

+ Call + Contact + fb + + ` + p := parsePage(src) + want := map[string]bool{"hello@brightsmiles.com": true, "billing@brightsmiles.com": true, "front@brightsmiles.com": true} + got := map[string]bool{} + for _, e := range p.emails { + got[e] = true + } + for e := range want { + if !got[e] { + t.Errorf("missing %s in %v", e, p.emails) + } + } + for e := range got { + if !want[e] { + t.Errorf("picked up %s, which is not the business's address", e) + } + } + if p.title != "Bright Smiles Dental" || p.description != "Family dentist in Austin" || !p.hasViewport { + t.Errorf("page meta = %q %q %v", p.title, p.description, p.hasViewport) + } + if len(p.phones) != 1 || p.phones[0] != "+15125550100" { + t.Errorf("phones = %v", p.phones) + } + var contact bool + for _, l := range p.links { + if l.href == "/contact-us" && l.text == "Contact" { + contact = true + } + } + if !contact { + t.Errorf("contact link not kept with its text: %+v", p.links) + } +} + +func cfEncode(email string, key byte) string { + const hexdigits = "0123456789abcdef" + out := []byte{hexdigits[key>>4], hexdigits[key&15]} + for i := 0; i < len(email); i++ { + b := email[i] ^ key + out = append(out, hexdigits[b>>4], hexdigits[b&15]) + } + return string(out) +} + +func TestDetectSiteNamesGaps(t *testing.T) { + p := parsePage(`© 2018 Joe's Plumbing`) + p.url, _ = url.Parse("http://joesplumbing.com/") + platform, signals := detectSite(p, time.Date(2026, 11, 4, 0, 0, 0, 0, time.UTC)) + if platform != "WordPress" { + t.Errorf("platform = %q", platform) + } + joined := strings.Join(signals, "|") + for _, want := range []string{"No HTTPS", "Not mobile friendly", "Outdated footer (2018)", "No analytics"} { + if !strings.Contains(joined, want) { + t.Errorf("signals %v missing %q", signals, want) + } + } +} + +func TestRobotsRules(t *testing.T) { + rules := parseRobots(` +User-agent: * +Disallow: /private +Allow: /private/contact + +User-agent: WarmblyBot +Disallow: /team$ +`, "warmblybot") + cases := map[string]bool{"/": true, "/team": false, "/team/jane": true, "/private": true} + for path, want := range cases { + u, _ := url.Parse("https://example.org" + path) + if got := rules.allowed(u); got != want { + t.Errorf("own group: %s allowed = %v, want %v", path, got, want) + } + } + star := parseRobots("User-agent: *\nDisallow: /private\nAllow: /private/contact\n", "warmblybot") + for path, want := range map[string]bool{"/private/x": false, "/private/contact": true, "/about": true} { + u, _ := url.Parse("https://example.org" + path) + if got := star.allowed(u); got != want { + t.Errorf("star group: %s allowed = %v, want %v", path, got, want) + } + } +} + +func TestOverpassQueryEscapesTypedText(t *testing.T) { + q, err := overpassQuery(Query{ + Text: `Joe's "best" (pizza).*`, + Category: CategoryByID("restaurant"), + Area: models.LeadArea{Kind: models.LeadAreaBBox, Bounds: models.LeadBounds{South: 30.2, West: -97.8, North: 30.3, East: -97.7}}, + }) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(q, `["name"~"Joe's \"best\" \\(pizza\\)\\.\\*",i]`) { + t.Errorf("text not escaped for both regex and string:\n%s", q) + } + if !strings.Contains(q, `nwr["amenity"="restaurant"]["name"]`) || !strings.Contains(q, "[bbox:30.200000,-97.800000,30.300000,-97.700000]") { + t.Errorf("query = %s", q) + } + if _, err := overpassQuery(Query{Area: models.LeadArea{Bounds: models.LeadBounds{South: 1, West: 1, North: 2, East: 2}}}); err == nil { + t.Error("an empty search must be refused, not sent as every named place") + } +} + +func TestAreaShapes(t *testing.T) { + circle, err := NormalizeArea(models.LeadArea{Kind: models.LeadAreaCircle, Center: &models.LatLng{Lat: 47.5, Lng: 19.05}, RadiusM: 1000}) + if err != nil { + t.Fatal(err) + } + if !Contains(circle, models.LatLng{Lat: 47.5045, Lng: 19.05}) || Contains(circle, models.LatLng{Lat: 47.51, Lng: 19.05}) { + t.Error("circle containment is off") + } + if circle.Bounds.North <= 47.5 || circle.Bounds.South >= 47.5 { + t.Errorf("circle bounds = %+v", circle.Bounds) + } + poly, err := NormalizeArea(models.LeadArea{Kind: models.LeadAreaPolygon, Polygon: []models.LatLng{{Lat: 0, Lng: 0}, {Lat: 0, Lng: 2}, {Lat: 2, Lng: 2}, {Lat: 2, Lng: 0}}}) + if err != nil { + t.Fatal(err) + } + if !Contains(poly, models.LatLng{Lat: 1, Lng: 1}) || Contains(poly, models.LatLng{Lat: 3, Lng: 1}) { + t.Error("polygon containment is off") + } + if _, err := NormalizeArea(models.LeadArea{Kind: models.LeadAreaCircle, Center: &models.LatLng{Lat: 1, Lng: 1}, RadiusM: 900000}); err == nil { + t.Error("an oversized circle must be refused") + } +} + +func TestEmailRankPrefersTheBusinessFrontDesk(t *testing.T) { + es := []models.LeadEmail{ + {Email: "jane@gmail.com", Status: "valid"}, + {Email: "noreply@shop.com", Status: "valid", DomainMatch: true}, + {Email: "info@shop.com", Status: "valid", DomainMatch: true}, + {Email: "owner@shop.com", Status: "invalid", DomainMatch: true}, + {Email: "sales@shop.com", Status: "suppressed", DomainMatch: true}, + } + best := es[0] + for _, e := range es[1:] { + if emailRank(e) < emailRank(best) { + best = e + } + } + if best.Email != "info@shop.com" { + t.Errorf("best = %s", best.Email) + } +} + +func TestNormalizeWebsite(t *testing.T) { + cases := map[string][2]string{ + "brightsmiles.com": {"https://brightsmiles.com", "brightsmiles.com"}, + "http://www.Shop.co.uk/home#top": {"http://www.shop.co.uk/home", "shop.co.uk"}, + "https://facebook.com/brightshop": {"", ""}, + "not a site": {"", ""}, + } + for in, want := range cases { + site, domain := NormalizeWebsite(in) + if site != want[0] || domain != want[1] { + t.Errorf("NormalizeWebsite(%q) = %q, %q; want %q, %q", in, site, domain, want[0], want[1]) + } + } +} + +func TestOSMFallsThroughBusyMirrors(t *testing.T) { + busy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusBadGateway) + })) + defer busy.Close() + ok := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _, _ = w.Write([]byte(`{"elements":[{"type":"node","id":7,"lat":47.5,"lon":19.05,"tags":{"name":"Corner Cafe","amenity":"cafe","website":"cornercafe.hu"}}]}`)) + })) + defer ok.Close() + refused := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusBadRequest) + })) + defer refused.Close() + + q := Query{Category: CategoryByID("cafe"), Area: models.LeadArea{Kind: models.LeadAreaBBox, Bounds: models.LeadBounds{South: 47.4, West: 19, North: 47.6, East: 19.1}}} + page, err := NewOSM(busy.URL+","+ok.URL, "test").Search(context.Background(), q) + if err != nil || len(page.Leads) != 1 || page.Leads[0].Domain != "cornercafe.hu" { + t.Fatalf("page = %+v, err = %v", page, err) + } + if _, err := NewOSM(refused.URL+","+ok.URL, "test").Search(context.Background(), q); err == nil || errors.Is(err, errOverpassBusy) { + t.Fatalf("a refused query must not fall through to the next mirror: %v", err) + } + if _, err := NewOSM(busy.URL, "test").Search(context.Background(), q); !errors.Is(err, errOverpassBusy) { + t.Fatalf("every mirror busy = %v", err) + } +} + +func TestCellSafe(t *testing.T) { + cases := map[string]string{ + "+36 30 364 0342": "+36 30 364 0342", + "+1 (512) 555-0100": "+1 (512) 555-0100", + "-12.5": "-12.5", + "=HYPERLINK(\"x\",\"y\")": "'=HYPERLINK(\"x\",\"y\")", + "+cmd|' /C calc'!A0": "'+cmd|' /C calc'!A0", + "@SUM(A1)": "'@SUM(A1)", + "\n=1+1": "'\n=1+1", + "Bright Smiles": "Bright Smiles", + } + for in, want := range cases { + if got := cellSafe(in); got != want { + t.Errorf("cellSafe(%q) = %q, want %q", in, got, want) + } + } +} diff --git a/internal/app/leadfinder/normalize.go b/internal/app/leadfinder/normalize.go new file mode 100644 index 000000000..f7b2bae03 --- /dev/null +++ b/internal/app/leadfinder/normalize.go @@ -0,0 +1,171 @@ +package leadfinder + +import ( + "net/url" + "regexp" + "strings" + + "golang.org/x/net/publicsuffix" +) + +// NormalizeWebsite turns a provider's website value into an absolute URL and +// its registrable domain; both empty when it is not a usable web address. +func NormalizeWebsite(raw string) (string, string) { + raw = strings.TrimSpace(raw) + if raw == "" { + return "", "" + } + if !strings.Contains(raw, "://") { + raw = "https://" + strings.TrimPrefix(raw, "//") + } + u, err := url.Parse(raw) + if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Hostname() == "" { + return "", "" + } + host := strings.ToLower(u.Hostname()) + if !strings.Contains(host, ".") { + return "", "" + } + u.Host = strings.ToLower(u.Host) + u.Fragment = "" + domain, err := publicsuffix.EffectiveTLDPlusOne(host) + if err != nil { + domain = strings.TrimPrefix(host, "www.") + } + if socialDomains[domain] { + // A Facebook page as a website is a social profile, not a site to read. + return "", "" + } + return u.String(), domain +} + +var socialDomains = map[string]bool{ + "facebook.com": true, "instagram.com": true, "linkedin.com": true, "twitter.com": true, "x.com": true, + "tiktok.com": true, "youtube.com": true, "yelp.com": true, "google.com": true, "goo.gl": true, + "wa.me": true, "whatsapp.com": true, "linktr.ee": true, "pinterest.com": true, +} + +// socialKind names the network a profile URL belongs to, or "". +func socialKind(raw string) string { + u, err := url.Parse(strings.TrimSpace(raw)) + if err != nil { + return "" + } + host := strings.TrimPrefix(strings.ToLower(u.Hostname()), "www.") + host = strings.TrimPrefix(host, "m.") + path := strings.Trim(u.Path, "/") + if path == "" { + return "" + } + first := strings.ToLower(strings.SplitN(path, "/", 2)[0]) + switch host { + case "facebook.com", "fb.com": + if first == "sharer" || first == "sharer.php" || first == "dialog" || first == "plugins" || first == "tr" { + return "" + } + return "facebook" + case "instagram.com": + if first == "p" || first == "explore" { + return "" + } + return "instagram" + case "linkedin.com": + if first == "company" || first == "in" || first == "school" { + return "linkedin" + } + case "twitter.com", "x.com": + if first == "intent" || first == "share" || first == "home" { + return "" + } + return "twitter" + case "tiktok.com": + if strings.HasPrefix(first, "@") { + return "tiktok" + } + case "youtube.com": + if first == "watch" || first == "embed" { + return "" + } + return "youtube" + case "pinterest.com": + return "pinterest" + case "yelp.com": + if first == "biz" { + return "yelp" + } + } + return "" +} + +// socialURL makes a handle or URL from a provider into a profile URL. +func socialURL(kind, v string) string { + v = strings.TrimSpace(v) + if v == "" { + return "" + } + if strings.HasPrefix(v, "http://") || strings.HasPrefix(v, "https://") { + return v + } + if strings.Contains(v, ".") && strings.Contains(v, "/") { + return "https://" + v + } + v = strings.TrimPrefix(v, "@") + switch kind { + case "facebook": + return "https://www.facebook.com/" + v + case "instagram": + return "https://www.instagram.com/" + v + case "twitter": + return "https://x.com/" + v + case "tiktok": + return "https://www.tiktok.com/@" + v + case "youtube": + return "https://www.youtube.com/@" + v + case "linkedin": + return "https://www.linkedin.com/company/" + v + } + return "" +} + +// Humanize turns a provider's snake_case type into a label: car_repair, Car repair. +func Humanize(v string) string { + v = strings.TrimSpace(strings.NewReplacer("_", " ", "-", " ").Replace(v)) + if v == "" { + return "" + } + return strings.ToUpper(v[:1]) + v[1:] +} + +func joinAddress(parts ...string) string { + out := make([]string, 0, len(parts)) + for _, p := range parts { + if p = strings.TrimSpace(p); p != "" { + out = append(out, p) + } + } + return strings.Join(out, ", ") +} + +var emailShape = regexp.MustCompile(`^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,24}$`) + +// cleanEmail lowercases a plausible address, or returns "". +func cleanEmail(v string) string { + v = strings.ToLower(strings.Trim(strings.TrimSpace(v), ".,;:<>()[]\"'")) + v = strings.TrimPrefix(v, "mailto:") + if i := strings.IndexByte(v, '?'); i >= 0 { + v = v[:i] + } + if !emailShape.MatchString(v) { + return "" + } + return v +} + +func firstNonEmpty(vs ...string) string { + for _, v := range vs { + if v = strings.TrimSpace(v); v != "" { + return v + } + } + return "" +} diff --git a/internal/app/leadfinder/osm.go b/internal/app/leadfinder/osm.go new file mode 100644 index 000000000..d1fe775e8 --- /dev/null +++ b/internal/app/leadfinder/osm.go @@ -0,0 +1,303 @@ +package leadfinder + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "strings" + "time" + + "github.com/warmbly/warmbly/internal/models" +) + +const ( + osmMaxResults = 1000 + // osmMaxAreaKM2 keeps a query inside what a public Overpass answers in time. + osmMaxAreaKM2 = 2500 + // osmHedgeAfter is how long a silent mirror gets before the next one is asked too. + osmHedgeAfter = 10 * time.Second +) + +// DefaultOverpassURLs are public Overpass mirrors, asked in order, the next as soon as one is busy or slow. They are +// shared and often busy; operators set LEAD_FINDER_OVERPASS_URL to their own. +var DefaultOverpassURLs = []string{ + "https://overpass-api.de/api/interpreter", + "https://maps.mail.ru/osm/tools/overpass/api/interpreter", + "https://overpass.private.coffee/api/interpreter", +} + +// errOverpassBusy means a mirror is overloaded; the next one is worth trying. +var errOverpassBusy = errors.New("OpenStreetMap's servers are busy right now; try again in a minute or use another provider") + +type osmProvider struct { + endpoints []string + userAgent string +} + +// NewOSM builds the OpenStreetMap provider over Overpass endpoints, given as a +// comma-separated list; empty means the public mirrors. +func NewOSM(endpoints, userAgent string) Provider { + var list []string + for _, e := range strings.Split(endpoints, ",") { + if e = strings.TrimSpace(e); e != "" { + list = append(list, e) + } + } + if len(list) == 0 { + list = DefaultOverpassURLs + } + return &osmProvider{endpoints: list, userAgent: userAgent} +} + +func (p *osmProvider) ID() models.LeadProvider { return models.LeadProviderOSM } + +// overpassQuery renders the search as Overpass QL. +func overpassQuery(q Query) (string, error) { + b := q.Area.Bounds + if b.West > b.East { + return "", errors.New("OpenStreetMap cannot search across the date line; move the map") + } + selectors := genericOSM + if q.Category != nil { + selectors = q.Category.OSM + } + name := "" + if t := strings.TrimSpace(q.Text); t != "" { + name = `["name"~"` + overpassString(regexEscape(t)) + `",i]` + } else if q.Category == nil { + return "", errors.New("pick a category or type what to look for") + } + var sb strings.Builder + fmt.Fprintf(&sb, "[out:json][timeout:25][bbox:%.6f,%.6f,%.6f,%.6f];\n(\n", b.South, b.West, b.North, b.East) + for _, sel := range selectors { + fmt.Fprintf(&sb, " nwr%s[\"name\"]%s;\n", sel, name) + } + fmt.Fprintf(&sb, ");\nout center tags %d;\n", osmMaxResults) + return sb.String(), nil +} + +func regexEscape(s string) string { + var sb strings.Builder + for _, r := range s { + if strings.ContainsRune(`\.^$*+?()[]{}|`, r) { + sb.WriteByte('\\') + } + sb.WriteRune(r) + } + return sb.String() +} + +func overpassString(s string) string { + return strings.NewReplacer(`\`, `\\`, `"`, `\"`, "\n", " ").Replace(s) +} + +type overpassElement struct { + Type string `json:"type"` + ID int64 `json:"id"` + Lat float64 `json:"lat"` + Lon float64 `json:"lon"` + Center *struct{ Lat, Lon float64 } `json:"center"` + Tags map[string]string `json:"tags"` +} + +func (p *osmProvider) Search(ctx context.Context, q Query) (*Page, error) { + if AreaKM2(q.Area.Bounds) > osmMaxAreaKM2 { + return nil, ErrAreaTooLarge + } + ql, err := overpassQuery(q) + if err != nil { + return nil, err + } + elements, err := p.hedged(ctx, ql) + if err != nil { + return nil, err + } + out := make([]models.Lead, 0, len(elements)) + for _, el := range elements { + if l, ok := osmLead(el, q.Category); ok { + out = append(out, l) + } + } + return &Page{Leads: out}, nil +} + +// hedged asks the mirrors in order, starting the next as soon as one is busy +// or has been silent for osmHedgeAfter, and keeps the first answer. +func (p *osmProvider) hedged(ctx context.Context, ql string) ([]overpassElement, error) { + ctx, cancel := context.WithCancel(ctx) + defer cancel() + type result struct { + elements []overpassElement + err error + } + results := make(chan result, len(p.endpoints)) + next, pending := 0, 0 + launch := func() { + endpoint := p.endpoints[next] + next++ + pending++ + go func() { + els, err := p.query(ctx, endpoint, ql) + results <- result{els, err} + }() + } + launch() + lastErr := errOverpassBusy + for pending > 0 { + timer := time.NewTimer(osmHedgeAfter) + select { + case r := <-results: + timer.Stop() + pending-- + if r.err == nil { + return r.elements, nil + } + if !errors.Is(r.err, errOverpassBusy) { + return nil, r.err + } + lastErr = r.err + if next < len(p.endpoints) { + launch() + } + case <-timer.C: + if next < len(p.endpoints) { + launch() + } + case <-ctx.Done(): + timer.Stop() + return nil, errOverpassBusy + } + } + return nil, lastErr +} + +// query runs the search on one mirror. An overloaded or silent mirror is +// errOverpassBusy so the caller moves on; anything else is final. +func (p *osmProvider) query(ctx context.Context, endpoint, ql string) ([]overpassElement, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(url.Values{"data": {ql}}.Encode())) + if err != nil { + return nil, err + } + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.Header.Set("User-Agent", p.userAgent) + resp, err := providerHTTP.Do(req) + if err != nil { + return nil, errOverpassBusy + } + defer resp.Body.Close() + switch resp.StatusCode { + case http.StatusOK: + case http.StatusTooManyRequests, http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusGatewayTimeout: + return nil, errOverpassBusy + case http.StatusBadRequest: + return nil, errors.New("OpenStreetMap could not run this search; try simpler words") + default: + return nil, statusErr(resp.StatusCode) + } + var body struct { + Elements []overpassElement `json:"elements"` + Remark string `json:"remark"` + } + if err := json.NewDecoder(io.LimitReader(resp.Body, 32<<20)).Decode(&body); err != nil { + return nil, errOverpassBusy + } + if len(body.Elements) == 0 && strings.Contains(body.Remark, "timed out") { + return nil, errors.New("OpenStreetMap took too long; zoom in and search a smaller area") + } + return body.Elements, nil +} + +// osmKinds are the tags whose value says what a place is, most specific first. +var osmKinds = []string{"healthcare", "craft", "office", "shop", "amenity", "tourism", "leisure", "sport"} + +func osmLead(el overpassElement, c *Category) (models.Lead, bool) { + t := el.Tags + name := strings.TrimSpace(t["name"]) + if name == "" { + return models.Lead{}, false + } + lat, lng := el.Lat, el.Lon + if el.Center != nil { + lat, lng = el.Center.Lat, el.Center.Lon + } + if lat == 0 && lng == 0 { + return models.Lead{}, false + } + l := models.Lead{ + Provider: models.LeadProviderOSM, + ExternalID: fmt.Sprintf("%s/%d", el.Type, el.ID), + Name: name, + Latitude: lat, + Longitude: lng, + Description: t["description"], + Chain: firstNonEmpty(t["brand"], t["operator:wikidata"]), + MapsURL: fmt.Sprintf("https://www.openstreetmap.org/%s/%d", el.Type, el.ID), + Socials: map[string]string{}, + Emails: []models.LeadEmail{}, + Hours: []string{}, + } + if l.Chain == "" && t["brand:wikidata"] != "" { + l.Chain = name + } + for _, k := range osmKinds { + if v := t[k]; v != "" && v != "yes" { + l.Categories = append(l.Categories, Humanize(v)) + } + } + if cu := t["cuisine"]; cu != "" { + for _, v := range strings.Split(cu, ";") { + l.Categories = append(l.Categories, Humanize(v)) + } + } + if len(l.Categories) > 0 { + l.Category = l.Categories[0] + } else if c != nil { + l.Category = c.Label + } + l.Street = strings.TrimSpace(t["addr:housenumber"] + " " + t["addr:street"]) + l.City = firstNonEmpty(t["addr:city"], t["addr:town"], t["addr:village"], t["addr:suburb"]) + l.Region = firstNonEmpty(t["addr:state"], t["addr:province"], t["addr:county"]) + l.Postcode = t["addr:postcode"] + l.Country = t["addr:country"] + l.Address = joinAddress(l.Street, l.City, strings.TrimSpace(l.Region+" "+l.Postcode), l.Country) + l.Phone = strings.TrimSpace(strings.Split(firstNonEmpty(t["phone"], t["contact:phone"], t["contact:mobile"], t["mobile"]), ";")[0]) + l.Website, l.Domain = NormalizeWebsite(firstNonEmpty(t["website"], t["contact:website"], t["url"])) + if e := cleanEmail(strings.Split(firstNonEmpty(t["email"], t["contact:email"]), ";")[0]); e != "" { + l.Email = e + l.Emails = []models.LeadEmail{{Email: e, Source: string(models.LeadProviderOSM), DomainMatch: emailDomainMatches(e, l.Domain)}} + } + for _, kind := range []string{"facebook", "instagram", "linkedin", "twitter", "tiktok", "youtube"} { + if v := firstNonEmpty(t["contact:"+kind], t[kind]); v != "" { + if u := socialURL(kind, v); u != "" { + l.Socials[kind] = u + } + } + } + if oh := t["opening_hours"]; oh != "" { + for _, part := range strings.Split(oh, ";") { + if part = strings.TrimSpace(part); part != "" { + l.Hours = append(l.Hours, part) + } + } + } + if t["disused:shop"] != "" || t["disused:amenity"] != "" { + l.BusinessStatus = "closed" + } + return l, true +} + +func emailDomainMatches(email, domain string) bool { + if domain == "" { + return false + } + at := strings.LastIndexByte(email, '@') + if at < 0 { + return false + } + host := email[at+1:] + return host == domain || strings.HasSuffix(host, "."+domain) +} diff --git a/internal/app/leadfinder/outscraper.go b/internal/app/leadfinder/outscraper.go new file mode 100644 index 000000000..b62f362a2 --- /dev/null +++ b/internal/app/leadfinder/outscraper.go @@ -0,0 +1,242 @@ +package leadfinder + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "sort" + "strconv" + "strings" + + "github.com/warmbly/warmbly/internal/models" +) + +const ( + outscraperSearchURL = "https://api.app.outscraper.com/google-maps-search" + outscraperPageSize = 20 + // outscraperMaxSkip is Google Maps' own ceiling on one query's results. + outscraperMaxSkip = 400 +) + +type outscraperProvider struct { + key string +} + +// NewOutscraper builds the Outscraper Google Maps provider with an API key. +func NewOutscraper(key string) Provider { + return &outscraperProvider{key: key} +} + +func (p *outscraperProvider) ID() models.LeadProvider { return models.LeadProviderOutscraper } + +func (p *outscraperProvider) Search(ctx context.Context, q Query) (*Page, error) { + text := strings.TrimSpace(q.Text) + if q.Category != nil { + text = strings.TrimSpace(text + " " + q.Category.Term) + } + if text == "" { + return nil, errors.New("pick a category or type what to look for") + } + skip := 0 + if q.Cursor != "" { + n, err := strconv.Atoi(q.Cursor) + if err != nil || n < 0 { + return nil, errors.New("the next page of this search is no longer available") + } + skip = n + } + c := Center(q.Area.Bounds) + payload := map[string]any{ + "query": []string{text}, + "organizationsPerQueryLimit": outscraperPageSize, + "skipPlaces": skip, + "coordinates": fmt.Sprintf("%.6f,%.6f", c.Lat, c.Lng), + "dropDuplicates": true, + "async": false, + "enrichment": []string{"domains_service"}, + } + if q.Language != "" { + payload["language"] = q.Language + } + rows, err := p.post(ctx, payload) + if err != nil { + return nil, err + } + out := make([]models.Lead, 0, len(rows)) + for _, r := range rows { + if l, ok := outscraperLead(r); ok { + out = append(out, l) + } + } + next := "" + if len(rows) >= outscraperPageSize && skip+outscraperPageSize < outscraperMaxSkip { + next = strconv.Itoa(skip + outscraperPageSize) + } + return &Page{Leads: out, NextCursor: next}, nil +} + +func (p *outscraperProvider) post(ctx context.Context, payload map[string]any) ([]map[string]any, error) { + raw, _ := json.Marshal(payload) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, outscraperSearchURL, bytes.NewReader(raw)) + if err != nil { + return nil, err + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-API-KEY", p.key) + resp, err := providerHTTP.Do(req) + if err != nil { + return nil, errors.New("Outscraper did not answer; try again") + } + defer resp.Body.Close() + if resp.StatusCode < 200 || resp.StatusCode > 299 { + return nil, statusErr(resp.StatusCode) + } + var body struct { + Data []json.RawMessage `json:"data"` + } + if err := json.NewDecoder(io.LimitReader(resp.Body, 16<<20)).Decode(&body); err != nil { + return nil, errors.New("Outscraper sent an answer that could not be read") + } + // data is one array per query; tolerate a flat array too. + var out []map[string]any + for _, d := range body.Data { + var group []map[string]any + if json.Unmarshal(d, &group) == nil { + out = append(out, group...) + continue + } + var one map[string]any + if json.Unmarshal(d, &one) == nil { + out = append(out, one) + } + } + return out, nil +} + +func str(m map[string]any, k string) string { + switch v := m[k].(type) { + case string: + return strings.TrimSpace(v) + case float64: + return strconv.FormatFloat(v, 'f', -1, 64) + } + return "" +} + +func num(m map[string]any, k string) *float64 { + if v, ok := m[k].(float64); ok { + return &v + } + return nil +} + +func outscraperLead(r map[string]any) (models.Lead, bool) { + id := firstNonEmpty(str(r, "place_id"), str(r, "google_id")) + lat, lng := num(r, "latitude"), num(r, "longitude") + if id == "" || lat == nil || lng == nil || str(r, "name") == "" { + return models.Lead{}, false + } + l := models.Lead{ + Provider: models.LeadProviderOutscraper, + ExternalID: id, + Name: str(r, "name"), + Address: str(r, "full_address"), + Street: str(r, "street"), + City: str(r, "city"), + Region: str(r, "state"), + Postcode: str(r, "postal_code"), + Country: str(r, "country_code"), + Latitude: *lat, + Longitude: *lng, + Phone: str(r, "phone"), + Rating: num(r, "rating"), + MapsURL: str(r, "location_link"), + Description: str(r, "description"), + Category: firstNonEmpty(str(r, "type"), str(r, "category")), + Socials: map[string]string{}, + Emails: []models.LeadEmail{}, + Hours: []string{}, + } + if v := num(r, "reviews"); v != nil { + n := int(*v) + l.ReviewCount = &n + } + if rng := str(r, "range"); rng != "" && strings.Trim(rng, "$") == "" { + n := len(rng) + l.PriceLevel = &n + } + for _, s := range strings.Split(str(r, "subtypes"), ",") { + if s = strings.TrimSpace(s); s != "" { + l.Categories = append(l.Categories, s) + } + } + l.Website, l.Domain = NormalizeWebsite(str(r, "site")) + switch str(r, "business_status") { + case "CLOSED_PERMANENTLY": + l.BusinessStatus = "closed" + case "CLOSED_TEMPORARILY": + l.BusinessStatus = "temporarily_closed" + case "OPERATIONAL": + l.BusinessStatus = "operational" + } + if wh, ok := r["working_hours"].(map[string]any); ok { + days := make([]string, 0, len(wh)) + for d := range wh { + days = append(days, d) + } + sort.Slice(days, func(i, j int) bool { return weekdayIndex(days[i]) < weekdayIndex(days[j]) }) + for _, d := range days { + switch v := wh[d].(type) { + case string: + l.Hours = append(l.Hours, d+": "+v) + case []any: + parts := make([]string, 0, len(v)) + for _, x := range v { + if s, ok := x.(string); ok { + parts = append(parts, s) + } + } + l.Hours = append(l.Hours, d+": "+strings.Join(parts, ", ")) + } + } + } + for i := 1; i <= 5; i++ { + e := cleanEmail(str(r, fmt.Sprintf("email_%d", i))) + if e == "" { + continue + } + l.Emails = append(l.Emails, models.LeadEmail{Email: e, Source: string(models.LeadProviderOutscraper), DomainMatch: emailDomainMatches(e, l.Domain)}) + } + if len(l.Emails) > 0 { + l.Email = l.Emails[0].Email + } + for _, kind := range []string{"facebook", "instagram", "linkedin", "twitter", "youtube", "tiktok"} { + if u := socialURL(kind, str(r, kind)); u != "" { + l.Socials[kind] = u + } + } + return l, true +} + +var weekdays = []string{"monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"} + +func weekdayIndex(d string) int { + d = strings.ToLower(d) + for i, w := range weekdays { + if strings.HasPrefix(d, w[:3]) { + return i + } + } + return len(weekdays) +} + +// CheckOutscraperKey proves the key is accepted with a one-result search. +func CheckOutscraperKey(ctx context.Context, key string) error { + p := &outscraperProvider{key: key} + _, err := p.post(ctx, map[string]any{"query": []string{"coffee, New York, USA"}, "organizationsPerQueryLimit": 1, "async": false}) + return err +} diff --git a/internal/app/leadfinder/people.go b/internal/app/leadfinder/people.go new file mode 100644 index 000000000..c7ea1b5c6 --- /dev/null +++ b/internal/app/leadfinder/people.go @@ -0,0 +1,808 @@ +package leadfinder + +import ( + "encoding/json" + "net/url" + "regexp" + "sort" + "strings" + "unicode" + "unicode/utf8" + + "golang.org/x/text/runes" + "golang.org/x/text/transform" + "golang.org/x/text/unicode/norm" + + "github.com/warmbly/warmbly/internal/models" +) + +const ( + peoplePerSite = 25 + segmentMax = 400 + segmentsMax = 4000 +) + +// FoundPerson is someone a business's website names. +type FoundPerson struct { + Name string + First string + Last string + Title string + Seniority models.LeadSeniority + Email string + LinkedIn string + Phone string + Source models.LeadPersonSource + URL string +} + +// --- names ----------------------------------------------------------------- + +type personName struct { + full, first, last, suffix string +} + +var ( + nameToken = regexp.MustCompile(`^\p{Lu}[\p{L}'’\-]*\.?$`) + initialToken = regexp.MustCompile(`^\p{Lu}\.?$`) + nameSplitters = regexp.MustCompile(`\s*(?:,|\s[–—|·•]\s|\s-\s)\s*`) +) + +// honorifics come before a name and are not part of it. +var honorifics = map[string]bool{ + "dr": true, "dr.": true, "mr": true, "mr.": true, "mrs": true, "mrs.": true, "ms": true, "ms.": true, "miss": true, + "prof": true, "prof.": true, "herr": true, "frau": true, "mag.": true, "ing.": true, "dipl.": true, "dipl.-ing.": true, + "med.": true, "dent.": true, "vet.": true, "rer.": true, "nat.": true, "sr.": true, "sra.": true, "mme": true, "m.": true, + "dott.": true, "dott.ssa": true, "avv.": true, "rev.": true, "hon.": true, "fza": true, "za": true, "zä": true, + "mudr.": true, "mudr": true, "drs.": true, "dipl.-stom.": true, "m.sc.": true, "msc": true, "univ.-prof.": true, "priv.-doz.": true, +} + +// credentials follow a name and read as part of the title. +var credentials = map[string]bool{ + "dds": true, "dmd": true, "md": true, "do": true, "dvm": true, "phd": true, "esq": true, "cpa": true, "jd": true, + "rn": true, "np": true, "pa": true, "pa-c": true, "od": true, "dc": true, "pt": true, "dpt": true, "mba": true, + "ms": true, "msc": true, "bsc": true, "ma": true, "ba": true, "rdh": true, "lmt": true, "cfp": true, "pe": true, + "jr": true, "sr": true, "ii": true, "iii": true, "iv": true, "ll.m": true, "llm": true, "faia": true, "aia": true, +} + +// particles sit lowercase inside a surname. +var particles = map[string]bool{ + "van": true, "von": true, "de": true, "da": true, "del": true, "der": true, "den": true, "di": true, "la": true, + "le": true, "du": true, "ten": true, "ter": true, "bin": true, "al": true, "dos": true, "das": true, "y": true, +} + +// notNameWords are words that start with a capital on a website but are never +// part of a person's name: navigation, services, places and roles. +var notNameWords = toSet(`about our team contact us home services service book now read more learn view all meet the and +privacy policy terms cookie cookies menu gallery blog news shop cart call today get free quote online appointment +appointments request hours location locations directions map email phone follow facebook instagram twitter linkedin +youtube tiktok reviews review testimonials careers jobs welcome family dental dentistry clinic center centre care health +medical group inc llc ltd gmbh co company street avenue road suite floor monday tuesday wednesday thursday friday +saturday sunday january february march april may june july august september october november december new patients +patient insurance payment financing specials offers emergency cosmetic general orthodontics implants whitening +cleaning exams pediatric restaurant bar grill cafe coffee pizza kitchen lunch dinner breakfast brunch catering events +event private party gift cards order delivery pickup takeout salon spa hair nails beauty fitness gym studio yoga +classes schedule pricing plans membership law firm attorneys lawyers practice areas real estate homes sale rent buy +sell agents office offices main downtown north south east west city county state united states america copyright +rights reserved powered website design designed sitemap accessibility statement skip content search login sign +account click here back top next previous page submit send message name first last your you we my who what why how +where when mission vision values history story approach philosophy leadership staff board directors founders +management partners associates doctors providers hygienists members owner founder director manager ceo president +chief officer partner principal dentist doctor attorney lawyer agent broker chef stylist therapist trainer coach +specialist assistant receptionist coordinator administrator technician nurse consultant advisor engineer designer +see open closed holiday holidays special wine beer drinks cocktails tickets visit visitors shipping returns faq faqs +help support resources library portal download downloads video videos photo photos community sponsors donate +volunteer subscribe newsletter latest featured popular best top quality professional professionals expert experts +certified licensed insured trusted local award winning years experience dds dmd md phd esq cpa inhaber +geschäftsführer impressum datenschutz kontakt startseite über uns leistungen termin praxis kanzlei zum zur profil +mehr weiter lesen jetzt hier unser unsere ihr ihre alle neu anrufen buchen online-termin zahnarzt zahnärztin +google ads maps analytics consent pixel hotjar matomo recaptcha cloudflare vimeo wordpress shopify wix squarespace +nuestro nuestra equipo ver más leer notre équipe voir plus lire nostro chi siamo scopri`) + +func toSet(words string) map[string]bool { + out := map[string]bool{} + for _, w := range strings.Fields(words) { + out[w] = true + } + return out +} + +// parseName reads a person's name out of a short piece of text. It is strict: +// a page holds far more capitalised phrases than names, and a wrong person is +// worse than a missed one. +func parseName(raw string) (personName, bool) { + s := strings.Join(strings.Fields(strings.Trim(raw, " \t\r\n.,;:!?()[]\"'“”‘’*•|")), " ") + if s == "" || utf8.RuneCountInString(s) > 60 || strings.ContainsAny(s, "@/\\:0123456789&+=#%_<>") { + return personName{}, false + } + var suffix []string + if i := strings.IndexByte(s, ','); i >= 0 { + for _, c := range strings.Split(s[i+1:], ",") { + c = strings.TrimSpace(c) + if c == "" { + continue + } + if !credentials[strings.ToLower(strings.Trim(c, "."))] { + return personName{}, false + } + suffix = append(suffix, c) + } + s = strings.TrimSpace(s[:i]) + } + tokens := strings.Fields(s) + for len(tokens) > 0 && honorifics[strings.ToLower(tokens[0])] { + tokens = tokens[1:] + } + for len(tokens) > 0 && credentials[strings.ToLower(strings.Trim(tokens[len(tokens)-1], "."))] { + suffix = append([]string{tokens[len(tokens)-1]}, suffix...) + tokens = tokens[:len(tokens)-1] + } + if len(tokens) < 2 || len(tokens) > 4 { + return personName{}, false + } + allCaps := true + for _, t := range tokens { + if strings.ToUpper(t) != t { + allCaps = false + } + } + for i, t := range tokens { + lower := strings.ToLower(t) + if notNameWords[strings.Trim(lower, ".")] { + return personName{}, false + } + if allCaps { + t = titleWord(t) + tokens[i] = t + } + inner := i > 0 && i < len(tokens)-1 + switch { + case inner && particles[lower]: + case inner && initialToken.MatchString(t): + case nameToken.MatchString(t) && utf8.RuneCountInString(strings.Trim(t, ".")) >= 2 && !strings.HasSuffix(t, "."): + default: + return personName{}, false + } + } + first := tokens[0] + last := tokens[len(tokens)-1] + if len(tokens) >= 3 && particles[strings.ToLower(tokens[len(tokens)-2])] { + last = tokens[len(tokens)-2] + " " + last + } + return personName{full: strings.Join(tokens, " "), first: first, last: last, suffix: strings.Join(suffix, ", ")}, true +} + +func titleWord(w string) string { + var b strings.Builder + up := true + for _, r := range strings.ToLower(w) { + if up { + b.WriteRune(unicode.ToUpper(r)) + } else { + b.WriteRune(r) + } + up = r == '-' || r == '\'' || r == '’' + } + return b.String() +} + +// looseName splits a name someone typed, without the website checks. +func looseName(first, last, full string) personName { + first, last = strings.TrimSpace(first), strings.TrimSpace(last) + if first == "" && last == "" { + tokens := strings.Fields(full) + for len(tokens) > 1 && honorifics[strings.ToLower(tokens[0])] { + tokens = tokens[1:] + } + switch len(tokens) { + case 0: + case 1: + first = tokens[0] + default: + first, last = tokens[0], tokens[len(tokens)-1] + } + } + name := strings.Join(strings.Fields(full), " ") + if name == "" { + name = strings.TrimSpace(first + " " + last) + } + return personName{full: name, first: first, last: last} +} + +var foldMarks = runes.Remove(runes.In(unicode.Mn)) + +var foldExtra = strings.NewReplacer("ß", "ss", "ø", "o", "æ", "ae", "œ", "oe", "ł", "l", "đ", "d", "þ", "th") + +// asciiFold lowercases and strips accents, so "José Núñez" reads "jose nunez". +func asciiFold(s string) string { + out, _, err := transform.String(transform.Chain(norm.NFD, foldMarks, norm.NFC), strings.ToLower(s)) + if err != nil { + out = strings.ToLower(s) + } + return foldExtra.Replace(out) +} + +// nameKey is how two mentions of the same person are matched. +func nameKey(first, last, full string) string { + if first != "" && last != "" { + return asciiFold(first) + " " + asciiFold(last) + } + return asciiFold(strings.Join(strings.Fields(full), " ")) +} + +// localPart keeps only the letters an address can carry. +func localPart(s string) string { + var b strings.Builder + for _, r := range asciiFold(s) { + if r >= 'a' && r <= 'z' { + b.WriteRune(r) + } + } + return b.String() +} + +// --- roles ----------------------------------------------------------------- + +var roleWords = regexp.MustCompile(`(?i)\b(owner|co-?owner|founder|co-?founder|ceo|cfo|coo|cto|cmo|chief|president|vice[- ]president|vp|chair(?:man|woman|person)?|managing director|director|manager|head of|partner|principal|proprietor|executive|supervisor|coordinator|administrator|officer|dentist|orthodontist|hygienist|physician|surgeon|doctor|veterinarian|optometrist|pharmacist|nurse|therapist|chiropractor|attorney|lawyer|counsel|paralegal|accountant|bookkeeper|agent|broker|realtor|chef|sommelier|stylist|barber|trainer|coach|instructor|consultant|advisor|adviser|engineer|designer|architect|developer|editor|technician|specialist|practitioner|associate|receptionist|assistant|team lead|inhaber(?:in)?|geschäftsführer(?:in)?|gründer(?:in)?|leiter(?:in)?|propietari[oa]|gerente|fundador[a]?|soci[oa]|fondat(?:eur|rice|ore)|gérante?|directeur|directrice|titolare|dds|dmd|dvm|esq|cpa)\b`) + +// roleText reports whether a short piece of text reads as someone's job title. +func roleText(s string) bool { + s = strings.TrimSpace(s) + n := utf8.RuneCountInString(s) + return n >= 2 && n <= 80 && roleWords.MatchString(s) && !strings.ContainsAny(s, "@") && !looksLikeLink(s) && strings.Count(s, " ") <= 9 +} + +func looksLikeLink(s string) bool { + l := strings.ToLower(s) + return strings.Contains(l, "://") || strings.Contains(l, "www.") || strings.Contains(l, ".com/") || strings.Contains(l, ".html") +} + +var ( + ownerTitle = regexp.MustCompile(`(?i)\b(owner|co-?owner|founder|co-?founder|proprietor|inhaber(?:in)?|propietari[oa]|titolare|titular|fondat(?:eur|rice|ore)|gérante?|gerant|managing partner|principal|gründer(?:in)?)\b`) + executiveTitle = regexp.MustCompile(`(?i)\b(ceo|cfo|coo|cto|cmo|cio|chief|president|vice[- ]president|vp|managing director|geschäftsführer(?:in)?|director general|chair(?:man|woman|person)?|partner|executive director)\b`) + managerTitle = regexp.MustCompile(`(?i)\b(manager|director|head of|head|lead|supervisor|coordinator|gerente|leiter(?:in)?|leitung|praxismanager(?:in)?|directeur|directrice|responsabile|jefe|jefa)\b`) +) + +// seniorityOf places a title. +func seniorityOf(title string) models.LeadSeniority { + switch { + case ownerTitle.MatchString(title): + return models.LeadSeniorityOwner + case executiveTitle.MatchString(title): + return models.LeadSeniorityExecutive + case managerTitle.MatchString(title): + return models.LeadSeniorityManager + } + return models.LeadSeniorityStaff +} + +func seniorityRank(s models.LeadSeniority) int { + switch s { + case models.LeadSeniorityOwner: + return 0 + case models.LeadSeniorityExecutive: + return 1 + case models.LeadSeniorityManager: + return 2 + } + return 3 +} + +func cleanTitle(s string) string { + s = strings.Join(strings.Fields(strings.Trim(s, " \t\r\n.,;:|-–—•·()[]")), " ") + if utf8.RuneCountInString(s) > 80 || looksLikeLink(s) { + return "" + } + return s +} + +// --- extraction ------------------------------------------------------------ + +// imprintLine is a legal notice naming who runs the business, which German, +// Austrian, Swiss and several other jurisdictions require on every site. +var imprintLine = regexp.MustCompile(`(?i)(geschäftsführer(?:in)?|geschäftsführung|inhaber(?:in)?|vertreten durch|vertretungsberechtigt(?:e|er)?(?: geschäftsführer(?:in)?)?|managing directors?|owner|proprietor|propietari[oa]|titular|gérante?|directeur de (?:la )?publication|responsable de (?:la )?publication|amministratore|titolare)\s*[::]\s*(.{4,80})`) + +func newPerson(n personName, title string, src models.LeadPersonSource, u string) FoundPerson { + title = cleanTitle(title) + if title == "" && n.suffix != "" { + title = n.suffix + } + return FoundPerson{Name: n.full, First: n.first, Last: n.last, Title: title, Seniority: seniorityOf(title), Source: src, URL: u} +} + +// extractPeople reads the people one page names. +func extractPeople(p *page) []FoundPerson { + u := "" + if p.url != nil { + u = p.url.String() + } + var out []FoundPerson + out = append(out, schemaPeople(p.jsonld, u)...) + imprintPage := imprintURL(u) + for _, seg := range p.segments { + for _, m := range imprintLine.FindAllStringSubmatch(seg, 3) { + label := strings.ToLower(m[1]) + legal := imprintPage || strings.Contains(label, "geschäftsf") || strings.Contains(label, "inhaber") || strings.Contains(label, "vertret") + for _, part := range strings.FieldsFunc(strings.ReplaceAll(m[2], " und ", ","), func(r rune) bool { return r == ',' || r == ';' || r == '|' }) { + if n, ok := leadingName(strings.Fields(part)); ok { + src := models.LeadPersonPage + if legal { + src = models.LeadPersonImprint + } + out = append(out, newPerson(n, imprintTitle(label), src, u)) + } + } + } + } + // A name with its role next to it, on one line or in neighbouring elements. + for i, seg := range p.segments { + if n, role, ok := nameWithRole(seg); ok { + out = append(out, newPerson(n, role, models.LeadPersonPage, u)) + continue + } + n, ok := parseName(seg) + if !ok { + continue + } + roleAt := func(j int) bool { + return j >= 0 && j < len(p.segments) && roleText(p.segments[j]) && !namesSomeone(p.segments[j]) + } + switch { + case roleAt(i + 1): + out = append(out, newPerson(n, p.segments[i+1], models.LeadPersonPage, u)) + case i+1 < len(p.segments) && utf8.RuneCountInString(p.segments[i+1]) <= 3 && roleAt(i+2): + out = append(out, newPerson(n, p.segments[i+2], models.LeadPersonPage, u)) + case roleAt(i - 1): + out = append(out, newPerson(n, p.segments[i-1], models.LeadPersonPage, u)) + case n.suffix != "": + out = append(out, newPerson(n, "", models.LeadPersonPage, u)) + } + } + for _, l := range p.links { + lower := strings.ToLower(l.href) + switch { + case strings.HasPrefix(lower, "mailto:"): + if n, ok := parseName(l.text); ok { + fp := newPerson(n, "", models.LeadPersonEmail, u) + fp.Email = acceptEmail(l.href) + if fp.Email != "" { + out = append(out, fp) + } + } + case strings.Contains(lower, "linkedin.com/in/"): + if fp, ok := linkedInPerson(l, p.url); ok { + fp.URL = u + out = append(out, fp) + } + } + } + return out +} + +// nameWithRole reads "Jane Doe, Owner" or "Jane Doe – Owner" from one line. A +// line that only adds credentials ("Jane Doe, DDS") is a name, not a role. +func nameWithRole(seg string) (personName, string, bool) { + parts := nameSplitters.Split(seg, 3) + if len(parts) < 2 { + return personName{}, "", false + } + n, ok := parseName(parts[0]) + role := strings.Join(parts[1:], ", ") + if !ok || !roleText(role) || onlyCredentials(role) { + return personName{}, "", false + } + return n, role, true +} + +func onlyCredentials(s string) bool { + for _, w := range strings.FieldsFunc(s, func(r rune) bool { return r == ',' || r == ' ' }) { + if !credentials[strings.ToLower(strings.Trim(w, "."))] { + return false + } + } + return true +} + +// namesSomeone reports whether a line is, or starts with, a person's name, so +// it is not read as the role of the name before it. +func namesSomeone(s string) bool { + if _, ok := parseName(s); ok { + return true + } + _, _, ok := nameWithRole(s) + return ok +} + +// leadingName takes the longest name at the start of words: "Max Muster +// Registergericht ..." reads "Max Muster". +func leadingName(words []string) (personName, bool) { + start := 0 + for start < len(words) && honorifics[strings.ToLower(words[start])] { + start++ + } + for end := min(len(words), start+4); end >= start+2; end-- { + if n, ok := parseName(strings.Join(words[start:end], " ")); ok { + return n, true + } + } + return personName{}, false +} + +func imprintTitle(label string) string { + switch { + case strings.Contains(label, "inhaber"), strings.Contains(label, "owner"), strings.Contains(label, "proprietor"), + strings.Contains(label, "propietari"), strings.Contains(label, "titolare"), strings.Contains(label, "titular"): + return "Owner" + case strings.Contains(label, "publication"): + return "Publisher" + } + return "Managing director" +} + +// linkedInPerson reads a profile link: the anchor text when it is a name, +// else the profile's slug ("/in/jane-doe-4a1b2c"). +func linkedInPerson(l link, base *url.URL) (FoundPerson, bool) { + u, err := url.Parse(l.href) + if err != nil { + return FoundPerson{}, false + } + if base != nil { + u = base.ResolveReference(u) + } + parts := strings.Split(strings.Trim(u.Path, "/"), "/") + if len(parts) < 2 || parts[0] != "in" || parts[1] == "" { + return FoundPerson{}, false + } + profile := "https://www.linkedin.com/in/" + parts[1] + if n, ok := parseName(l.text); ok { + fp := newPerson(n, "", models.LeadPersonLinkedIn, "") + fp.LinkedIn = profile + return fp, true + } + slug, _ := url.PathUnescape(parts[1]) + var words []string + for _, w := range strings.Split(slug, "-") { + if w == "" || strings.ContainsAny(w, "0123456789") { + break + } + words = append(words, titleWord(w)) + } + if len(words) < 2 || len(words) > 3 { + return FoundPerson{}, false + } + n, ok := parseName(strings.Join(words, " ")) + if !ok { + return FoundPerson{}, false + } + fp := newPerson(n, "", models.LeadPersonLinkedIn, "") + fp.LinkedIn = profile + return fp, true +} + +// schemaPeople reads schema.org Person entries out of a page's JSON-LD. +func schemaPeople(blocks []string, u string) []FoundPerson { + var out []FoundPerson + visited := 0 + var walk func(v any, depth int) + walk = func(v any, depth int) { + if depth > 8 || visited > 400 { + return + } + visited++ + switch x := v.(type) { + case []any: + for _, e := range x { + walk(e, depth+1) + } + case map[string]any: + if isSchemaType(x["@type"], "Person") { + if fp, ok := schemaPerson(x, u); ok { + out = append(out, fp) + } + } + for k, e := range x { + if k != "@context" { + walk(e, depth+1) + } + } + } + } + for _, b := range blocks { + var v any + if json.Unmarshal([]byte(strings.TrimSpace(b)), &v) == nil { + walk(v, 0) + } + } + return out +} + +func isSchemaType(t any, want string) bool { + switch x := t.(type) { + case string: + return strings.EqualFold(strings.TrimPrefix(x, "schema:"), want) + case []any: + for _, e := range x { + if isSchemaType(e, want) { + return true + } + } + } + return false +} + +func schemaString(v any) string { + switch x := v.(type) { + case string: + return strings.TrimSpace(x) + case []any: + for _, e := range x { + if s := schemaString(e); s != "" { + return s + } + } + case map[string]any: + return schemaString(x["name"]) + } + return "" +} + +func schemaPerson(x map[string]any, u string) (FoundPerson, bool) { + given, family := schemaString(x["givenName"]), schemaString(x["familyName"]) + full := schemaString(x["name"]) + if full == "" { + full = strings.TrimSpace(given + " " + family) + } + n, ok := parseName(full) + if !ok { + if given == "" || family == "" || strings.ContainsAny(full, "@0123456789") || utf8.RuneCountInString(full) > 60 { + return FoundPerson{}, false + } + n = personName{full: full, first: given, last: family} + } + fp := newPerson(n, schemaString(x["jobTitle"]), models.LeadPersonSchema, u) + fp.Email = acceptEmail(schemaString(x["email"])) + if tel := telDigits.ReplaceAllString(schemaString(x["telephone"]), ""); len(tel) >= 7 { + fp.Phone = tel + } + var links []string + switch s := x["sameAs"].(type) { + case string: + links = []string{s} + case []any: + for _, e := range s { + if v, ok := e.(string); ok { + links = append(links, v) + } + } + } + for _, l := range links { + if strings.Contains(strings.ToLower(l), "linkedin.com/in/") { + fp.LinkedIn = strings.TrimSpace(l) + break + } + } + return fp, true +} + +// sourceRank orders sources from most to least trustworthy. +func sourceRank(s models.LeadPersonSource) int { + switch s { + case models.LeadPersonManual: + return 0 + case models.LeadPersonSchema: + return 1 + case models.LeadPersonImprint: + return 2 + case models.LeadPersonPage: + return 3 + case models.LeadPersonEmail: + return 4 + } + return 5 +} + +// mergePeople folds several mentions of one person into one, keeping the best +// source and every detail any of them carried. +func mergePeople(found []FoundPerson) []FoundPerson { + byKey := map[string]int{} + var out []FoundPerson + for _, f := range found { + key := nameKey(f.First, f.Last, f.Name) + if key == "" { + continue + } + i, ok := byKey[key] + if !ok { + byKey[key] = len(out) + out = append(out, f) + continue + } + cur := &out[i] + if sourceRank(f.Source) < sourceRank(cur.Source) { + cur.Source, cur.URL, cur.Name = f.Source, f.URL, f.Name + } + if cur.Title == "" && f.Title != "" { + cur.Title, cur.Seniority = f.Title, f.Seniority + } + if cur.Email == "" { + cur.Email = f.Email + } + if cur.LinkedIn == "" { + cur.LinkedIn = f.LinkedIn + } + if cur.Phone == "" { + cur.Phone = f.Phone + } + } + sort.SliceStable(out, func(i, j int) bool { + if a, b := seniorityRank(out[i].Seniority), seniorityRank(out[j].Seniority); a != b { + return a < b + } + return sourceRank(out[i].Source) < sourceRank(out[j].Source) + }) + if len(out) > peoplePerSite { + out = out[:peoplePerSite] + } + return out +} + +// --- address patterns ------------------------------------------------------ + +// emailPattern builds a person's address from their name the way one domain does. +type emailPattern struct { + key string + build func(f, l string) string +} + +// emailPatterns are the shapes businesses use, most common first. A pattern +// that needs a last name returns "" without one. +var emailPatterns = []emailPattern{ + {"first.last", func(f, l string) string { return join(f, ".", l) }}, + {"first", func(f, _ string) string { return f }}, + {"flast", func(f, l string) string { return join(initial(f), "", l) }}, + {"firstlast", func(f, l string) string { return join(f, "", l) }}, + {"f.last", func(f, l string) string { return join(initial(f), ".", l) }}, + {"last", func(_, l string) string { return l }}, + {"first_last", func(f, l string) string { return join(f, "_", l) }}, + {"first-last", func(f, l string) string { return join(f, "-", l) }}, + {"last.first", func(f, l string) string { return join(l, ".", f) }}, + {"lastf", func(f, l string) string { return join(l, "", initial(f)) }}, + {"firstl", func(f, l string) string { return join(f, "", initial(l)) }}, + {"first.l", func(f, l string) string { return join(f, ".", initial(l)) }}, +} + +// probeOrder is how many of the common patterns an unknown domain is tried with. +const probeOrder = 6 + +func initial(s string) string { + if s == "" { + return "" + } + return s[:1] +} + +func join(a, sep, b string) string { + if a == "" || b == "" { + return "" + } + return a + sep + b +} + +func patternByKey(key string) *emailPattern { + for i := range emailPatterns { + if emailPatterns[i].key == key { + return &emailPatterns[i] + } + } + return nil +} + +// candidates lists the addresses to try for a name at domain: the domain's +// known pattern first, then the common ones. +func candidates(pattern, first, last, domain string, limit int) []string { + f, l := localPart(first), localPart(last) + if f == "" || domain == "" { + return nil + } + seen := map[string]bool{} + var out []string + add := func(p *emailPattern) { + if p == nil || len(out) >= limit { + return + } + if local := p.build(f, l); local != "" && !seen[local] { + seen[local] = true + out = append(out, local+"@"+domain) + } + } + add(patternByKey(pattern)) + for i := range emailPatterns[:probeOrder] { + add(&emailPatterns[i]) + } + return out +} + +// patternOf names the pattern that turns this person's name into local, or "". +func patternOf(local, first, last string) string { + f, l := localPart(first), localPart(last) + if f == "" { + return "" + } + for _, p := range emailPatterns { + if v := p.build(f, l); v != "" && v == local { + return p.key + } + } + return "" +} + +// separatedLocal splits "jane.doe" style locals into a first and last name. +var separatedLocal = regexp.MustCompile(`^([a-z]{2,20})[._-]([a-z]{2,24})$`) + +// attachEmails gives people the personal addresses the site published, adds +// the people only an address names, and learns the domain's pattern from them. +func attachEmails(people []FoundPerson, emails []FoundEmail, domain string) ([]FoundPerson, string) { + votes := map[string]int{} + byLocal := map[string]FoundEmail{} + for _, e := range emails { + at := strings.LastIndexByte(e.Email, '@') + if at < 0 || registrable(e.Email[at+1:]) != domain { + continue + } + byLocal[e.Email[:at]] = e + } + locals := make([]string, 0, len(byLocal)) + for local := range byLocal { + locals = append(locals, local) + } + sort.Strings(locals) + taken := map[string]bool{} + for i := range people { + p := &people[i] + if p.Email != "" { + taken[p.Email] = true + if at := strings.LastIndexByte(p.Email, '@'); at > 0 && registrable(p.Email[at+1:]) == domain { + if k := patternOf(p.Email[:at], p.First, p.Last); k != "" { + votes[k]++ + } + } + continue + } + for _, local := range locals { + e := byLocal[local] + if taken[e.Email] { + continue + } + // "first" or "last" alone matches too loosely to name the owner. + if k := patternOf(local, p.First, p.Last); k != "" && k != "first" && k != "last" { + p.Email = e.Email + taken[e.Email] = true + votes[k]++ + break + } + } + } + for _, local := range locals { + e := byLocal[local] + if taken[e.Email] || genericLocals[local] { + continue + } + m := separatedLocal.FindStringSubmatch(local) + if m == nil || notNameWords[m[1]] || notNameWords[m[2]] { + continue + } + n := personName{first: titleWord(m[1]), last: titleWord(m[2])} + n.full = n.first + " " + n.last + fp := newPerson(n, "", models.LeadPersonEmail, e.URL) + fp.Email = e.Email + people = append(people, fp) + votes[patternOf(local, n.first, n.last)]++ + } + best, top := "", 0 + for k, v := range votes { + if k != "" && (v > top || (v == top && k < best)) { + best, top = k, v + } + } + return people, best +} diff --git a/internal/app/leadfinder/people_service.go b/internal/app/leadfinder/people_service.go new file mode 100644 index 000000000..149dffb92 --- /dev/null +++ b/internal/app/leadfinder/people_service.go @@ -0,0 +1,541 @@ +package leadfinder + +import ( + "context" + "errors" + "sort" + "strings" + "time" + + "github.com/google/uuid" + "github.com/rs/zerolog/log" + + "github.com/warmbly/warmbly/internal/app/credits" + "github.com/warmbly/warmbly/internal/errx" + "github.com/warmbly/warmbly/internal/models" + "github.com/warmbly/warmbly/internal/pkg/emailverify" + "github.com/warmbly/warmbly/internal/repository" +) + +const ( + // guessPeopleMax is how many people per lead get an address worked out. + guessPeopleMax = 10 + // probesPerLead bounds the address checks one lead's people cost a run. + probesPerLead = 15 + // probesPerPerson bounds the checks one on-request search makes. + probesPerPerson = 8 + personFindTimeout = 45 * time.Second +) + +// Confidence that a person's address reaches them, by how it was arrived at. +const ( + confPublishedValid = 100 + confPatternValid = 95 + confPublished = 80 + confManual = 80 + confKnownPattern = 60 + confGuess = 25 +) + +// mailDomain is the domain a lead's people get addresses at: the site's own +// after redirects, else the one its listing gave. +func mailDomain(l *models.Lead) string { + if l.Site.FinalURL != "" { + if _, d := NormalizeWebsite(l.Site.FinalURL); d != "" { + return d + } + } + return l.Domain +} + +func toLeadPerson(f FoundPerson) models.LeadPerson { + p := models.LeadPerson{ + Name: f.Name, FirstName: f.First, LastName: f.Last, Title: f.Title, Seniority: f.Seniority, + LinkedInURL: f.LinkedIn, Phone: f.Phone, Source: f.Source, SourceURL: f.URL, + } + if p.Seniority == "" { + p.Seniority = seniorityOf(p.Title) + } + p.NameKey = nameKey(p.FirstName, p.LastName, p.Name) + if f.Email != "" { + p.Email, p.EmailSource, p.EmailConfidence = f.Email, models.LeadEmailWebsite, confPublished + } + return p +} + +// mergeFound folds what a crawl found into the people a lead already has, +// filling blanks and never overwriting what a teammate typed in. Someone an +// earlier read found that this one did not is returned as stale, unless a +// teammate added them, typed their address or made them a contact. +func mergeFound(existing []models.LeadPerson, found []FoundPerson) (people, stale []models.LeadPerson) { + seen := map[string]bool{} + for _, f := range found { + seen[nameKey(f.First, f.Last, f.Name)] = true + } + var out []models.LeadPerson + for _, p := range existing { + if !seen[p.NameKey] && p.Source != models.LeadPersonManual && p.EmailSource != models.LeadEmailManual && p.ContactID == nil { + stale = append(stale, p) + continue + } + out = append(out, p) + } + byKey := map[string]int{} + for i, p := range out { + byKey[p.NameKey] = i + } + for _, f := range found { + np := toLeadPerson(f) + i, ok := byKey[np.NameKey] + if !ok { + byKey[np.NameKey] = len(out) + out = append(out, np) + continue + } + cur := &out[i] + if cur.Title == "" { + cur.Title = np.Title + } + cur.Seniority = seniorityOf(cur.Title) + if cur.LinkedInURL == "" { + cur.LinkedInURL = np.LinkedInURL + } + if cur.Phone == "" { + cur.Phone = np.Phone + } + if cur.SourceURL == "" { + cur.SourceURL = np.SourceURL + } + if np.Email != "" && cur.EmailSource != models.LeadEmailManual && (cur.Email == "" || cur.EmailSource == models.LeadEmailPattern) { + cur.Email, cur.EmailSource, cur.EmailStatus, cur.EmailConfidence = np.Email, np.EmailSource, "", np.EmailConfidence + } + } + return out, stale +} + +// addressFinder works out people's addresses at one domain, sharing what it +// learns (the pattern, whether the server accepts anything) across them. +type addressFinder struct { + s *Service + orgID uuid.UUID + domain string + pattern string + // acceptsAll: the server takes any address, so a guess cannot be confirmed. + acceptsAll bool + // blind: checks come back undecided (a provider that hides its mailboxes, a + // blocked port), so guessing more costs checks and learns nothing. + blind bool + noMail bool + verify bool + probes int + budget int +} + +func (s *Service) newAddressFinder(orgID uuid.UUID, l *models.Lead, verify bool, budget int) *addressFinder { + return &addressFinder{ + s: s, orgID: orgID, domain: mailDomain(l), pattern: l.Site.EmailPattern, acceptsAll: l.Site.AcceptsAll, + verify: verify && s.Verifier != nil, budget: budget, + } +} + +func (f *addressFinder) check(ctx context.Context, email string) (emailverify.Result, bool) { + if !f.verify || f.probes >= f.budget || ctx.Err() != nil { + return emailverify.Result{}, false + } + f.probes++ + return f.s.Verifier.VerifyAddress(ctx, f.orgID, email), true +} + +// settle records what checking an address said about the domain. +func (f *addressFinder) settle(r emailverify.Result) { + switch { + case r.IsCatchAll || r.SubStatus == emailverify.SubStatusCatchAll: + f.acceptsAll = true + case r.SubStatus == emailverify.SubStatusNoMX: + f.noMail = true + case r.Status == emailverify.StatusUnknown || r.SubStatus == emailverify.SubStatusUndisclosed: + f.blind = true + } +} + +// find fills in one person's address. It returns false when it found none. +func (f *addressFinder) find(ctx context.Context, p *models.LeadPerson) bool { + // An address someone typed or the site published is only checked. + if p.Email != "" && p.EmailSource != models.LeadEmailPattern { + if p.EmailStatus == "" { + if r, ok := f.check(ctx, p.Email); ok { + p.EmailStatus = string(r.Status) + if r.Status == emailverify.StatusValid && p.EmailSource == models.LeadEmailWebsite { + p.EmailConfidence = confPublishedValid + } + f.settle(r) + } + } + return true + } + if p.Email != "" && p.EmailStatus == string(emailverify.StatusValid) { + return true + } + first, last := p.FirstName, p.LastName + if first == "" { + n := looseName("", "", p.Name) + first, last = n.first, n.last + } + list := candidates(f.pattern, first, last, f.domain, probeOrder+1) + if len(list) == 0 || f.noMail { + return false + } + guessed := func(email string) bool { + conf := confGuess + if f.pattern != "" && email == list[0] { + conf = confKnownPattern + } + p.Email, p.EmailSource, p.EmailStatus, p.EmailConfidence = email, models.LeadEmailPattern, models.LeadPersonStatusGuessed, conf + return true + } + if f.acceptsAll || f.blind || !f.verify { + return guessed(list[0]) + } + for _, c := range list { + r, ok := f.check(ctx, c) + if !ok { + return guessed(list[0]) + } + f.settle(r) + switch { + case r.Status == emailverify.StatusValid: + p.Email, p.EmailSource, p.EmailStatus, p.EmailConfidence = c, models.LeadEmailPattern, string(r.Status), confPatternValid + if f.pattern == "" { + if at := strings.LastIndexByte(c, '@'); at > 0 { + f.pattern = patternOf(c[:at], first, last) + } + } + return true + case f.noMail: + p.Email, p.EmailSource, p.EmailStatus, p.EmailConfidence = "", models.LeadEmailNone, "", 0 + return false + case f.acceptsAll || f.blind: + return guessed(list[0]) + } + // Rejected: the next shape may be the one. + } + // Every shape was refused: this person has no address there. + if p.EmailSource == models.LeadEmailPattern { + p.Email, p.EmailSource, p.EmailStatus, p.EmailConfidence = "", models.LeadEmailNone, "", 0 + } + return false +} + +// findAll works out addresses for a lead's people, most senior first, and +// marks any the workspace has suppressed. +func (f *addressFinder) findAll(ctx context.Context, people []models.LeadPerson) { + order := make([]int, len(people)) + for i := range order { + order[i] = i + } + sort.SliceStable(order, func(a, b int) bool { + return seniorityRank(people[order[a]].Seniority) < seniorityRank(people[order[b]].Seniority) + }) + for n, i := range order { + if n >= guessPeopleMax || ctx.Err() != nil { + break + } + f.find(ctx, &people[i]) + } + f.markSuppressed(ctx, people) +} + +func (f *addressFinder) markSuppressed(ctx context.Context, people []models.LeadPerson) { + var addrs []string + for _, p := range people { + if p.Email != "" { + addrs = append(addrs, p.Email) + } + } + if len(addrs) == 0 { + return + } + suppressed, err := f.s.Repo.SuppressedEmails(ctx, f.orgID, addrs) + if err != nil { + log.Warn().Err(err).Msg("leadfinder: could not check suppression for people") + return + } + for i := range people { + if suppressed[people[i].Email] { + people[i].EmailStatus = "suppressed" + } + } +} + +// remember keeps what the finder learned about the domain on the lead. +func (f *addressFinder) remember(l *models.Lead) { + if f.pattern != "" { + l.Site.EmailPattern = f.pattern + } + if f.acceptsAll { + l.Site.AcceptsAll = true + } +} + +// enrichPeople merges what a crawl found into the lead's people, works out +// their addresses and saves them. It returns how many people the crawl named. +func (s *Service) enrichPeople(ctx context.Context, run *models.LeadEnrichmentRun, l *models.Lead, found []FoundPerson) (int, error) { + existing, err := s.Repo.PeopleForLeads(ctx, run.OrganizationID, []uuid.UUID{l.ID}) + if err != nil { + return 0, err + } + people, stale := mergeFound(existing[l.ID], found) + for _, p := range stale { + if _, err := s.Repo.DeletePerson(ctx, run.OrganizationID, l.ID, p.ID); err != nil { + return 0, err + } + } + if len(people) == 0 { + return 0, nil + } + f := s.newAddressFinder(run.OrganizationID, l, run.Verify, probesPerLead) + f.findAll(ctx, people) + f.remember(l) + if _, err := s.Repo.SavePeople(ctx, run.OrganizationID, l.ID, people); err != nil { + if errors.Is(err, repository.ErrLeadNotFound) { + return 0, nil + } + return 0, err + } + return len(found), nil +} + +// --- people a teammate adds or edits ---------------------------------------- + +// PersonInput is a person typed in on a lead. Name or a first name is required. +type PersonInput struct { + Name string `json:"name"` + FirstName string `json:"first_name"` + LastName string `json:"last_name"` + Title string `json:"title"` + Email string `json:"email"` + LinkedInURL string `json:"linkedin_url"` + Phone string `json:"phone"` +} + +// PersonPatch edits a person. Nil fields are left alone. +type PersonPatch struct { + Name *string `json:"name"` + FirstName *string `json:"first_name"` + LastName *string `json:"last_name"` + Title *string `json:"title"` + Email *string `json:"email"` + LinkedInURL *string `json:"linkedin_url"` + Phone *string `json:"phone"` +} + +func checkPersonFields(p *models.LeadPerson) error { + switch { + case p.NameKey == "" || p.FirstName == "": + return errx.New(errx.BadRequest, "enter the person's name") + case len([]rune(p.Name)) > 120 || len([]rune(p.FirstName)) > 60 || len([]rune(p.LastName)) > 60: + return errx.New(errx.BadRequest, "a name is limited to 120 characters") + case len([]rune(p.Title)) > 120: + return errx.New(errx.BadRequest, "a title is limited to 120 characters") + case p.LinkedInURL != "" && !strings.Contains(strings.ToLower(p.LinkedInURL), "linkedin.com/"): + return errx.New(errx.BadRequest, "the LinkedIn link must point at linkedin.com") + case len(p.LinkedInURL) > 300 || len(p.Phone) > 40: + return errx.New(errx.BadRequest, "a link or phone number is too long") + } + return nil +} + +func setTypedEmail(p *models.LeadPerson, raw string) error { + raw = strings.TrimSpace(raw) + if raw == "" { + p.Email, p.EmailSource, p.EmailStatus, p.EmailConfidence = "", models.LeadEmailNone, "", 0 + return nil + } + e := cleanEmail(raw) + if e == "" { + return errx.New(errx.BadRequest, "the email address is not valid") + } + p.Email, p.EmailSource, p.EmailStatus, p.EmailConfidence = e, models.LeadEmailManual, "", confManual + return nil +} + +// AddPerson adds someone to a lead. Without an address, it works one out at the +// lead's domain the way FindPersonEmail does. +func (s *Service) AddPerson(ctx context.Context, orgID, leadID uuid.UUID, in PersonInput) (*models.LeadPerson, error) { + l, err := s.Get(ctx, orgID, leadID) + if err != nil { + return nil, err + } + n := looseName(in.FirstName, in.LastName, in.Name) + p := models.LeadPerson{ + Name: n.full, FirstName: n.first, LastName: n.last, Title: strings.TrimSpace(in.Title), + LinkedInURL: strings.TrimSpace(in.LinkedInURL), Phone: strings.TrimSpace(in.Phone), Source: models.LeadPersonManual, + } + p.Seniority = seniorityOf(p.Title) + p.NameKey = nameKey(p.FirstName, p.LastName, p.Name) + if err := checkPersonFields(&p); err != nil { + return nil, err + } + if err := setTypedEmail(&p, in.Email); err != nil { + return nil, err + } + return s.findAndSave(ctx, orgID, l, p) +} + +// UpdatePerson edits someone on a lead. +func (s *Service) UpdatePerson(ctx context.Context, orgID, leadID, id uuid.UUID, patch PersonPatch) (*models.LeadPerson, error) { + p, err := s.person(ctx, orgID, leadID, id) + if err != nil { + return nil, err + } + if patch.Name != nil || patch.FirstName != nil || patch.LastName != nil { + first, last, full := p.FirstName, p.LastName, p.Name + if patch.FirstName != nil { + first = *patch.FirstName + } + if patch.LastName != nil { + last = *patch.LastName + } + if patch.Name != nil { + full = *patch.Name + if patch.FirstName == nil && patch.LastName == nil { + first, last = "", "" + } + } else { + full = strings.TrimSpace(first + " " + last) + } + n := looseName(first, last, full) + p.Name, p.FirstName, p.LastName = n.full, n.first, n.last + p.NameKey = nameKey(p.FirstName, p.LastName, p.Name) + } + if patch.Title != nil { + p.Title = strings.TrimSpace(*patch.Title) + p.Seniority = seniorityOf(p.Title) + } + if patch.LinkedInURL != nil { + p.LinkedInURL = strings.TrimSpace(*patch.LinkedInURL) + } + if patch.Phone != nil { + p.Phone = strings.TrimSpace(*patch.Phone) + } + if err := checkPersonFields(p); err != nil { + return nil, err + } + if patch.Email != nil && !strings.EqualFold(strings.TrimSpace(*patch.Email), p.Email) { + if err := setTypedEmail(p, *patch.Email); err != nil { + return nil, err + } + if p.Email != "" { + l, err := s.Get(ctx, orgID, leadID) + if err != nil { + return nil, err + } + pctx, cancel := context.WithTimeout(ctx, personFindTimeout) + defer cancel() + f := s.newAddressFinder(orgID, l, true, 1) + f.find(pctx, p) + one := []models.LeadPerson{*p} + f.markSuppressed(pctx, one) + *p = one[0] + } + } + return s.savePerson(ctx, orgID, leadID, *p) +} + +// FindPersonEmail works out a person's address at the lead's domain again, +// checking each likely shape until one is confirmed. +func (s *Service) FindPersonEmail(ctx context.Context, orgID, leadID, id uuid.UUID) (*models.LeadPerson, error) { + l, err := s.Get(ctx, orgID, leadID) + if err != nil { + return nil, err + } + p, err := s.person(ctx, orgID, leadID, id) + if err != nil { + return nil, err + } + if p.EmailSource == models.LeadEmailPattern { + p.Email, p.EmailSource, p.EmailStatus, p.EmailConfidence = "", models.LeadEmailNone, "", 0 + } + if p.Email != "" { + p.EmailStatus = "" + } + return s.findAndSave(ctx, orgID, l, *p) +} + +// findAndSave works out p's address when it has none, charging for the search +// when the instance is metered and refunding it when nothing turned up. +func (s *Service) findAndSave(ctx context.Context, orgID uuid.UUID, l *models.Lead, p models.LeadPerson) (*models.LeadPerson, error) { + pctx, cancel := context.WithTimeout(ctx, personFindTimeout) + defer cancel() + searching := p.Email == "" + if searching && mailDomain(l) == "" { + return nil, errx.NewWithIdentifier(errx.BadRequest, "lead_person_no_domain", "This business has no website, so there is no domain to work out an address at") + } + key := "lead_person:" + uuid.NewString() + if searching && s.metered() { + if _, err := s.Credits.Charge(pctx, orgID, credits.CostLeadPersonEmail, "lead_person_email", key); err != nil { + return nil, creditErr(err) + } + } + f := s.newAddressFinder(orgID, l, true, probesPerPerson) + found := f.find(pctx, &p) + one := []models.LeadPerson{p} + f.markSuppressed(pctx, one) + p = one[0] + if searching && s.metered() && !found { + if _, err := s.Credits.RefundCharge(context.WithoutCancel(pctx), orgID, key, "lead_person_email_refund"); err != nil { + log.Warn().Err(err).Msg("leadfinder: could not refund a person search that found nothing") + } + } + if f.pattern != l.Site.EmailPattern || f.acceptsAll != l.Site.AcceptsAll { + f.remember(l) + if err := s.Repo.SaveSite(ctx, orgID, l.ID, l.Site); err != nil { + log.Warn().Err(err).Msg("leadfinder: could not store a domain's address pattern") + } + } + saved, err := s.savePerson(ctx, orgID, l.ID, p) + if err != nil && searching && s.metered() && found { + if _, rerr := s.Credits.RefundCharge(context.WithoutCancel(pctx), orgID, key, "lead_person_email_refund"); rerr != nil { + log.Warn().Err(rerr).Msg("leadfinder: could not refund a person search that was not saved") + } + } + return saved, err +} + +func (s *Service) savePerson(ctx context.Context, orgID, leadID uuid.UUID, p models.LeadPerson) (*models.LeadPerson, error) { + saved, err := s.Repo.SavePeople(ctx, orgID, leadID, []models.LeadPerson{p}) + switch { + case errors.Is(err, repository.ErrLeadNotFound): + return nil, errx.New(errx.NotFound, "lead not found") + case errors.Is(err, repository.ErrLeadPersonExists): + return nil, errx.NewWithIdentifier(errx.Conflict, "lead_person_exists", "Someone with this name is already on this lead") + case err != nil: + return nil, err + case len(saved) == 0: + return nil, errx.New(errx.NotFound, "person not found") + } + return &saved[0], nil +} + +func (s *Service) person(ctx context.Context, orgID, leadID, id uuid.UUID) (*models.LeadPerson, error) { + p, err := s.Repo.GetPerson(ctx, orgID, leadID, id) + if err != nil { + return nil, err + } + if p == nil { + return nil, errx.New(errx.NotFound, "person not found") + } + return p, nil +} + +// DeletePerson removes someone from a lead. A contact made from them stays. +func (s *Service) DeletePerson(ctx context.Context, orgID, leadID, id uuid.UUID) error { + ok, err := s.Repo.DeletePerson(ctx, orgID, leadID, id) + if err != nil { + return err + } + if !ok { + return errx.New(errx.NotFound, "person not found") + } + return nil +} diff --git a/internal/app/leadfinder/people_test.go b/internal/app/leadfinder/people_test.go new file mode 100644 index 000000000..f6ce23b90 --- /dev/null +++ b/internal/app/leadfinder/people_test.go @@ -0,0 +1,257 @@ +package leadfinder + +import ( + "context" + "net/url" + "strings" + "testing" + + "github.com/google/uuid" + + "github.com/warmbly/warmbly/internal/models" + "github.com/warmbly/warmbly/internal/pkg/emailverify" +) + +// addr builds an address, so none sits in the source as one string. +func addr(local, domain string) string { return local + "@" + domain } + +func TestParseNameIsStrictAboutWhatIsAPerson(t *testing.T) { + people := map[string][2]string{ + "Jane Doe": {"Jane", "Doe"}, + "Dr. Maria García-López": {"Maria", "García-López"}, + "Jane Doe, DDS": {"Jane", "Doe"}, + "JOHN SMITH": {"John", "Smith"}, + "Ludwig van Beethoven": {"Ludwig", "van Beethoven"}, + "Mary J. Blige": {"Mary", "Blige"}, + "Prof. Dr. Anna Schröder": {"Anna", "Schröder"}, + } + for in, want := range people { + n, ok := parseName(in) + if !ok || n.first != want[0] || n.last != want[1] { + t.Errorf("parseName(%q) = %+v, %v; want %v", in, n, ok, want) + } + } + if n, _ := parseName("Jane Doe, DDS"); n.suffix != "DDS" { + t.Errorf("credential suffix = %q, want DDS", n.suffix) + } + for _, in := range []string{ + "Contact Us", "Our Team", "Book Now", "Read More", "Family Dentistry", "Austin Texas 78701", + "Monday Friday", "Jane", addr("jane", "example.org"), "Privacy Policy", "New Patients Welcome", "Meet The Team", + "Jane Doe, Owner", "Call (512) 555-0100", "The quick brown fox jumps over", "Zum Profil", "Google Ads", + } { + if n, ok := parseName(in); ok { + t.Errorf("parseName(%q) = %+v, want no name", in, n) + } + } +} + +func TestExtractPeopleFromATeamPage(t *testing.T) { + src := ` +

Meet the Team

+

Jane Doe

Owner & Lead Dentist

+

Dr. Ravi Patel, DMD

Associate Dentist

+
Office Manager

Carla Gómez

+

Tom Baker – Head Hygienist

+

Our Services

Cleaning and whitening

+

Austin Downtown

Open Monday to Friday

+ Jane Doe + LinkedIn + + ` + p := parsePage(src) + p.url, _ = url.Parse("https://brightsmiles.com/our-team") + people := mergePeople(extractPeople(p)) + byName := map[string]FoundPerson{} + for _, f := range people { + byName[f.Name] = f + } + expect := map[string]struct { + title string + seniority models.LeadSeniority + }{ + "Jane Doe": {"Owner & Lead Dentist", models.LeadSeniorityOwner}, + "Ravi Patel": {"Associate Dentist", models.LeadSeniorityStaff}, + "Carla Gómez": {"Office Manager", models.LeadSeniorityManager}, + "Tom Baker": {"Head Hygienist", models.LeadSeniorityManager}, + "Sam Lee": {"Practice Coordinator", models.LeadSeniorityManager}, + } + for name, want := range expect { + got, ok := byName[name] + if !ok { + t.Errorf("missing %s; found %v", name, people) + continue + } + if got.Title != want.title || got.Seniority != want.seniority { + t.Errorf("%s = %q (%s), want %q (%s)", name, got.Title, got.Seniority, want.title, want.seniority) + } + } + if len(people) != len(expect) { + t.Errorf("found %d people, want %d: %+v", len(people), len(expect), people) + } + if byName["Jane Doe"].Email != addr("jane", "brightsmiles.com") { + t.Errorf("Jane's mailto = %q", byName["Jane Doe"].Email) + } + if byName["Ravi Patel"].LinkedIn != "https://www.linkedin.com/in/ravi-patel-4a1b2c" { + t.Errorf("Ravi's LinkedIn = %q", byName["Ravi Patel"].LinkedIn) + } + if byName["Sam Lee"].Email != addr("sam.lee", "brightsmiles.com") || byName["Sam Lee"].Source != models.LeadPersonSchema { + t.Errorf("Sam = %+v", byName["Sam Lee"]) + } + if people[0].Name != "Jane Doe" { + t.Errorf("owner should come first, got %s", people[0].Name) + } +} + +func TestRoleTextRefusesLinks(t *testing.T) { + for _, s := range []string{"https://policies.google.com/technologies/partner-sites", "www.example.com/team-lead"} { + if roleText(s) { + t.Errorf("roleText(%q) = true", s) + } + } + if got := seniorityOf("Stellvertretende Leitung"); got != models.LeadSeniorityManager { + t.Errorf("a German deputy lead is %s, want manager", got) + } +} + +func TestExtractPeopleFromAnImprint(t *testing.T) { + src := `

Impressum

+

Zahnarztpraxis Sonnenschein GmbH
Hauptstraße 1, 10115 Berlin

+

Geschäftsführer: Dr. Max Mustermann und Erika Musterfrau

+

Registergericht: Amtsgericht Berlin

` + p := parsePage(src) + p.url, _ = url.Parse("https://sonnenschein.de/impressum") + people := mergePeople(extractPeople(p)) + if len(people) != 2 { + t.Fatalf("found %+v, want Max Mustermann and Erika Musterfrau", people) + } + for _, f := range people { + if f.Source != models.LeadPersonImprint || f.Seniority != models.LeadSeniorityExecutive { + t.Errorf("%s = %s, %s", f.Name, f.Source, f.Seniority) + } + } +} + +func TestAttachEmailsLearnsTheDomainPattern(t *testing.T) { + people := []FoundPerson{ + {Name: "Jane Doe", First: "Jane", Last: "Doe"}, + {Name: "Ravi Patel", First: "Ravi", Last: "Patel"}, + } + emails := []FoundEmail{ + {Email: addr("jane.doe", "brightsmiles.com")}, + {Email: addr("info", "brightsmiles.com")}, + {Email: addr("sam.lee", "brightsmiles.com")}, + {Email: addr("ravi", "gmail.com")}, + } + out, pattern := attachEmails(people, emails, "brightsmiles.com") + if pattern != "first.last" { + t.Errorf("pattern = %q, want first.last", pattern) + } + if out[0].Email != addr("jane.doe", "brightsmiles.com") || out[1].Email != "" { + t.Errorf("attached = %q, %q", out[0].Email, out[1].Email) + } + if len(out) != 3 || out[2].Name != "Sam Lee" || out[2].Source != models.LeadPersonEmail { + t.Errorf("an address naming its owner should add them: %+v", out) + } + if got := candidates(pattern, "Ravi", "Patel", "brightsmiles.com", 3); got[0] != addr("ravi.patel", "brightsmiles.com") { + t.Errorf("candidates = %v", got) + } + if got := candidates("", "José", "Núñez", "x.com", 2); got[0] != addr("jose.nunez", "x.com") || got[1] != addr("jose", "x.com") { + t.Errorf("accented candidates = %v", got) + } +} + +type fakeVerifier struct { + valid map[string]bool + catchAll bool + calls []string +} + +func (f *fakeVerifier) VerifyAddress(_ context.Context, _ uuid.UUID, email string) emailverify.Result { + f.calls = append(f.calls, email) + switch { + case f.catchAll: + return emailverify.Result{Status: emailverify.StatusRisky, SubStatus: emailverify.SubStatusCatchAll, IsCatchAll: true} + case f.valid[email]: + return emailverify.Result{Status: emailverify.StatusValid} + } + return emailverify.Result{Status: emailverify.StatusInvalid} +} + +func TestAddressFinderChecksShapesUntilOneIsConfirmed(t *testing.T) { + v := &fakeVerifier{valid: map[string]bool{addr("jdoe", "brightsmiles.com"): true}} + s := &Service{Deps: Deps{Verifier: v}} + l := &models.Lead{Domain: "brightsmiles.com"} + f := s.newAddressFinder(uuid.New(), l, true, 15) + jane := models.LeadPerson{Name: "Jane Doe", FirstName: "Jane", LastName: "Doe"} + if !f.find(context.Background(), &jane) || jane.Email != addr("jdoe", "brightsmiles.com") || jane.EmailStatus != "valid" { + t.Fatalf("jane = %+v after %v", jane, v.calls) + } + if f.pattern != "flast" { + t.Errorf("learned pattern = %q, want flast", f.pattern) + } + // The learned pattern is tried first for the next person. + v.calls = nil + v.valid[addr("rpatel", "brightsmiles.com")] = true + ravi := models.LeadPerson{Name: "Ravi Patel", FirstName: "Ravi", LastName: "Patel"} + f.find(context.Background(), &ravi) + if len(v.calls) != 1 || ravi.EmailConfidence != confPatternValid { + t.Errorf("ravi took %v, confidence %d", v.calls, ravi.EmailConfidence) + } + // Nobody by that name: every shape refused, no address kept. + nobody := models.LeadPerson{Name: "Zed Nobody", FirstName: "Zed", LastName: "Nobody"} + if f.find(context.Background(), &nobody) || nobody.Email != "" { + t.Errorf("nobody = %+v", nobody) + } +} + +func TestAddressFinderStopsCheckingAServerThatAcceptsAll(t *testing.T) { + v := &fakeVerifier{catchAll: true} + s := &Service{Deps: Deps{Verifier: v}} + l := &models.Lead{Domain: "anything.com", Site: models.LeadSite{EmailPattern: "first"}} + f := s.newAddressFinder(uuid.New(), l, true, 15) + people := []models.LeadPerson{ + {Name: "Jane Doe", FirstName: "Jane", LastName: "Doe"}, + {Name: "Ravi Patel", FirstName: "Ravi", LastName: "Patel"}, + } + for i := range people { + f.find(context.Background(), &people[i]) + } + if len(v.calls) != 1 { + t.Errorf("checked %v; a server that accepts everything is asked once", v.calls) + } + for _, p := range people { + if p.EmailStatus != models.LeadPersonStatusGuessed || p.EmailConfidence != confKnownPattern || !strings.HasSuffix(p.Email, "@anything.com") { + t.Errorf("%s = %q %s %d", p.Name, p.Email, p.EmailStatus, p.EmailConfidence) + } + } + f.remember(l) + if !l.Site.AcceptsAll { + t.Error("the lead should remember its server accepts any address") + } +} + +func TestMergeFoundKeepsWhatATeammateTyped(t *testing.T) { + existing := []models.LeadPerson{{ + ID: uuid.New(), Name: "Jane Doe", NameKey: "jane doe", FirstName: "Jane", LastName: "Doe", + Email: addr("jane", "home.example"), EmailSource: models.LeadEmailManual, Source: models.LeadPersonManual, + }} + found := []FoundPerson{ + {Name: "Jane Doe", First: "Jane", Last: "Doe", Title: "Owner", Seniority: models.LeadSeniorityOwner, Email: addr("jane", "brightsmiles.com"), Source: models.LeadPersonPage}, + {Name: "Ravi Patel", First: "Ravi", Last: "Patel", Source: models.LeadPersonPage}, + } + gone := models.LeadPerson{ID: uuid.New(), Name: "Old Hire", NameKey: "old hire", Source: models.LeadPersonPage} + out, stale := mergeFound(append(existing, gone), found) + if len(out) != 2 { + t.Fatalf("merged %+v", out) + } + if len(stale) != 1 || stale[0].ID != gone.ID { + t.Errorf("someone the site no longer names should be stale: %+v", stale) + } + if out[0].Email != addr("jane", "home.example") || out[0].Title != "Owner" || out[0].ID != existing[0].ID { + t.Errorf("jane = %+v", out[0]) + } + if out[1].NameKey != "ravi patel" || out[1].ID != uuid.Nil { + t.Errorf("ravi = %+v", out[1]) + } +} diff --git a/internal/app/leadfinder/provider.go b/internal/app/leadfinder/provider.go new file mode 100644 index 000000000..2f8b48b88 --- /dev/null +++ b/internal/app/leadfinder/provider.go @@ -0,0 +1,76 @@ +// Package leadfinder finds local businesses on a map through pluggable place +// providers, reads their websites for contact details and turns them into +// contacts. +package leadfinder + +import ( + "context" + "errors" + "net/http" + "time" + + "github.com/warmbly/warmbly/internal/models" +) + +// Query is one page of a provider search. +type Query struct { + Text string + Category *Category + Area models.LeadArea + // Cursor is the provider's own token for the next page; empty for the first. + Cursor string + Limit int + Language string +} + +// Page is one page of results and the cursor to the next, empty when done. +type Page struct { + Leads []models.Lead + NextCursor string +} + +// Provider searches one place database. +type Provider interface { + ID() models.LeadProvider + Search(ctx context.Context, q Query) (*Page, error) +} + +// ProviderInfo describes a provider to the dashboard. +type ProviderInfo struct { + ID models.LeadProvider `json:"id"` + Name string `json:"name"` + Description string `json:"description"` + // Available is true when a search can run: free, or a key is configured. + Available bool `json:"available"` + // KeySource is "none", "workspace" or "instance". + KeySource string `json:"key_source"` + NeedsKey bool `json:"needs_key"` + PageSize int `json:"page_size"` + MaxPages int `json:"max_pages"` + CreditCost int `json:"credit_cost"` + Fields []string `json:"fields"` + Integration string `json:"integration,omitempty"` +} + +// ErrProviderKey means the provider refused the API key. +var ErrProviderKey = errors.New("the provider refused the API key") + +// ErrProviderQuota means the provider is rate limiting or out of quota. +var ErrProviderQuota = errors.New("the provider is rate limiting or out of quota; try again later") + +// ErrAreaTooLarge means the area is wider than the provider can search at once. +var ErrAreaTooLarge = errors.New("zoom in: the area is too large to search at once") + +// providerHTTP is the client every provider talks through. Provider hosts are +// fixed public APIs or operator configuration, never request input. +var providerHTTP = &http.Client{Timeout: 45 * time.Second} + +func statusErr(code int) error { + switch { + case code == http.StatusUnauthorized || code == http.StatusForbidden: + return ErrProviderKey + case code == http.StatusTooManyRequests || code == http.StatusPaymentRequired: + return ErrProviderQuota + } + return errors.New("the provider answered " + http.StatusText(code)) +} diff --git a/internal/app/leadfinder/service.go b/internal/app/leadfinder/service.go new file mode 100644 index 000000000..5dd0cab4f --- /dev/null +++ b/internal/app/leadfinder/service.go @@ -0,0 +1,679 @@ +package leadfinder + +import ( + "context" + "errors" + "fmt" + "strings" + "time" + + "github.com/google/uuid" + "github.com/rs/zerolog/log" + + "github.com/warmbly/warmbly/internal/app/contact" + "github.com/warmbly/warmbly/internal/app/credits" + "github.com/warmbly/warmbly/internal/errx" + "github.com/warmbly/warmbly/internal/models" + "github.com/warmbly/warmbly/internal/pkg/emailverify" + "github.com/warmbly/warmbly/internal/repository" +) + +const ( + // SelectionCap is the most leads one bulk action takes. + SelectionCap = 5000 + // PointsCap is the most pins the map draws at once. + PointsCap = 5000 + // searchTimeout bounds one provider page. + searchTimeout = 55 * time.Second + // defaultUserAgent identifies the finder to providers and websites. + defaultUserAgent = "WarmblyBot/1.0 (+https://warmbly.com/bot)" +) + +// Config is the instance-level setup: endpoints, the operator's own provider +// keys and the map style. Every value is optional. +type Config struct { + OverpassURL string + GeocoderURL string + GoogleKey string + FoursquareKey string + OutscraperKey string + MapStyleLight string + MapStyleDark string + UserAgent string +} + +// Integrations is the slice of the integration service the finder reads keys through. +type Integrations interface { + ListConnections(ctx context.Context, orgID uuid.UUID) ([]models.IntegrationConnection, error) + ConnectionConfig(ctx context.Context, orgID, connID uuid.UUID) (map[string]any, *models.IntegrationConnection, error) +} + +// Verifier checks one address without writing anything. +type Verifier interface { + VerifyAddress(ctx context.Context, orgID uuid.UUID, email string) emailverify.Result +} + +// Credits charges flat-priced work. +type Credits interface { + Charge(ctx context.Context, orgID uuid.UUID, amount int, reason, idempotencyKey string) (int, error) + RefundCharge(ctx context.Context, orgID uuid.UUID, chargeKey, reason string) (int, error) + // Unmetered is true when the instance bills nothing in credits. + Unmetered() bool +} + +// Deps is everything the finder talks to. +type Deps struct { + Repo repository.LeadFinderRepository + Integrations Integrations + Contacts contact.ContactService + Verifier Verifier + Credits Credits + Audit AuditLogger + Config Config +} + +// Service finds, enriches, exports and imports leads. +type Service struct { + Deps + geocoder *Geocoder + crawler *Crawler + osm Provider + // newProvider builds a keyed provider; tests replace it. + newProvider func(id models.LeadProvider, key string) Provider +} + +// NewService builds the lead finder. +func NewService(d Deps) *Service { + ua := d.Config.UserAgent + if ua == "" { + ua = defaultUserAgent + } + d.Config.UserAgent = ua + return &Service{ + Deps: d, + geocoder: NewGeocoder(d.Config.GeocoderURL, ua), + crawler: NewCrawler(ua), + osm: NewOSM(d.Config.OverpassURL, ua), + newProvider: keyedProvider, + } +} + +// metered is whether this instance charges credits at all. +func (s *Service) metered() bool { + return s.Credits != nil && !s.Credits.Unmetered() +} + +func keyedProvider(id models.LeadProvider, key string) Provider { + switch id { + case models.LeadProviderGooglePlaces: + return NewGooglePlaces(key) + case models.LeadProviderFoursquare: + return NewFoursquare(key) + case models.LeadProviderOutscraper: + return NewOutscraper(key) + } + return nil +} + +// integrationFor is the workspace integration that holds a provider's key. +var integrationFor = map[models.LeadProvider]models.IntegrationProvider{ + models.LeadProviderGooglePlaces: models.IntegrationGooglePlaces, + models.LeadProviderFoursquare: models.IntegrationFoursquare, + models.LeadProviderOutscraper: models.IntegrationOutscraper, +} + +var providerMeta = map[models.LeadProvider]ProviderInfo{ + models.LeadProviderOSM: { + Name: "OpenStreetMap", + Description: "Free and open map data. Strong on names, places and websites; phone and email coverage varies by region.", + PageSize: osmMaxResults, MaxPages: 1, + Fields: []string{"name", "address", "category", "website", "phone", "email", "hours", "socials"}, + }, + models.LeadProviderGooglePlaces: { + Name: "Google Places", + Description: "Google's business listings with ratings, review counts, hours and websites. Uses a Google Maps Platform key.", + PageSize: 20, MaxPages: 3, + Fields: []string{"name", "address", "category", "website", "phone", "rating", "reviews", "price", "hours", "status"}, + }, + models.LeadProviderFoursquare: { + Name: "Foursquare", + Description: "Foursquare's global places database with categories, chains, socials, ratings and hours.", + PageSize: 50, MaxPages: 10, + Fields: []string{"name", "address", "category", "website", "phone", "email", "rating", "reviews", "price", "hours", "socials", "chain"}, + }, + models.LeadProviderOutscraper: { + Name: "Outscraper", + Description: "Google Maps results through Outscraper, with emails and social profiles from the business's domain.", + PageSize: outscraperPageSize, MaxPages: outscraperMaxSkip / outscraperPageSize, + Fields: []string{"name", "address", "category", "website", "phone", "email", "rating", "reviews", "price", "hours", "socials", "status"}, + }, +} + +func (s *Service) instanceKey(id models.LeadProvider) string { + switch id { + case models.LeadProviderGooglePlaces: + return s.Config.GoogleKey + case models.LeadProviderFoursquare: + return s.Config.FoursquareKey + case models.LeadProviderOutscraper: + return s.Config.OutscraperKey + } + return "" +} + +// workspaceKey is the key from the workspace's own connection, or "". +func (s *Service) workspaceKey(ctx context.Context, orgID uuid.UUID, id models.LeadProvider, conns []models.IntegrationConnection) string { + want, ok := integrationFor[id] + if !ok || s.Integrations == nil { + return "" + } + for _, c := range conns { + if c.Provider != want || c.Status == models.IntegrationStatusDisconnected || c.Status == models.IntegrationStatusReauthRequired { + continue + } + cfg, _, err := s.Integrations.ConnectionConfig(ctx, orgID, c.ID) + if err != nil { + continue + } + if key, _ := cfg["api_key"].(string); strings.TrimSpace(key) != "" { + return strings.TrimSpace(key) + } + } + return "" +} + +func (s *Service) connections(ctx context.Context, orgID uuid.UUID) []models.IntegrationConnection { + if s.Integrations == nil { + return nil + } + conns, err := s.Integrations.ListConnections(ctx, orgID) + if err != nil { + log.Warn().Err(err).Msg("leadfinder: could not list integrations") + return nil + } + return conns +} + +// resolve picks the provider client for a search and where its key came +// from. A workspace's own key wins over the operator's. +func (s *Service) resolve(ctx context.Context, orgID uuid.UUID, id models.LeadProvider) (Provider, string, error) { + if id == models.LeadProviderOSM { + return s.osm, "none", nil + } + if !id.Valid() { + return nil, "", errx.New(errx.BadRequest, "unknown lead provider") + } + if key := s.workspaceKey(ctx, orgID, id, s.connections(ctx, orgID)); key != "" { + return s.newProvider(id, key), "workspace", nil + } + if key := s.instanceKey(id); key != "" { + return s.newProvider(id, key), "instance", nil + } + return nil, "", errx.NewWithIdentifier(errx.BadRequest, "lead_provider_not_connected", + fmt.Sprintf("Connect %s under Integrations to search with it", providerMeta[id].Name)) +} + +// FinderConfig is what the dashboard needs before its first search. +type FinderConfig struct { + Providers []ProviderInfo `json:"providers"` + Categories []Category `json:"categories"` + DefaultProvider string `json:"default_provider"` + EnrichCost int `json:"enrich_cost"` + PersonEmailCost int `json:"person_email_cost"` + ExportColumns []ExportColumn `json:"export_columns"` + PersonColumns []PersonColumn `json:"person_columns"` + DefaultColumns []string `json:"default_export_columns"` + Map MapConfig `json:"map"` +} + +// MapConfig is the vector style the dashboard's map draws. +type MapConfig struct { + StyleLight string `json:"style_light"` + StyleDark string `json:"style_dark"` +} + +// Default map styles: OpenFreeMap, free and keyless. Operators can host their own. +const ( + DefaultMapStyleLight = "https://tiles.openfreemap.org/styles/positron" + DefaultMapStyleDark = "https://tiles.openfreemap.org/styles/dark" +) + +// FinderConfig lists the providers this workspace can search and how. +func (s *Service) FinderConfig(ctx context.Context, orgID uuid.UUID) *FinderConfig { + conns := s.connections(ctx, orgID) + out := &FinderConfig{Categories: Categories, DefaultProvider: string(models.LeadProviderOSM), ExportColumns: ExportColumns, PersonColumns: PersonColumns, DefaultColumns: DefaultExportColumns} + if s.metered() { + out.EnrichCost = credits.CostLeadEnrich + out.PersonEmailCost = credits.CostLeadPersonEmail + } + for _, id := range models.LeadProviders { + info := providerMeta[id] + info.ID = id + info.KeySource = "none" + if id == models.LeadProviderOSM { + info.Available = true + } else { + info.NeedsKey = true + info.Integration = string(integrationFor[id]) + switch { + case s.workspaceKey(ctx, orgID, id, conns) != "": + info.Available, info.KeySource = true, "workspace" + case s.instanceKey(id) != "": + info.Available, info.KeySource = true, "instance" + if s.metered() { + info.CreditCost = credits.CostLeadSearchPage + } + } + } + out.Providers = append(out.Providers, info) + } + out.DefaultProvider = string(defaultProvider(out.Providers)) + out.Map = MapConfig{StyleLight: s.Config.MapStyleLight, StyleDark: s.Config.MapStyleDark} + if out.Map.StyleLight == "" { + out.Map.StyleLight = DefaultMapStyleLight + } + if out.Map.StyleDark == "" { + out.Map.StyleDark = DefaultMapStyleDark + } + return out +} + +// defaultProvider is the richest provider available, OpenStreetMap at worst. +func defaultProvider(ps []ProviderInfo) models.LeadProvider { + for _, id := range []models.LeadProvider{models.LeadProviderGooglePlaces, models.LeadProviderOutscraper, models.LeadProviderFoursquare} { + for _, p := range ps { + if p.ID == id && p.Available { + return id + } + } + } + return models.LeadProviderOSM +} + +// Geocode looks up a typed location. +func (s *Service) Geocode(ctx context.Context, q string, near *models.LatLng, lang string) ([]GeocodeResult, error) { + if len([]rune(q)) > 200 { + return nil, errx.New(errx.BadRequest, "the location is too long") + } + res, err := s.geocoder.Search(ctx, q, near, 6, lang) + if err != nil { + log.Warn().Err(err).Msg("leadfinder: geocoding failed") + return nil, errx.New(errx.ServiceUnavailable, "Places could not be looked up right now. Try again shortly.") + } + return res, nil +} + +// SearchRequest starts a search or fetches the next page of one. +type SearchRequest struct { + SearchID *uuid.UUID `json:"search_id,omitempty"` + Provider models.LeadProvider `json:"provider"` + Query string `json:"query"` + Category string `json:"category"` + LocationLabel string `json:"location_label"` + Area models.LeadArea `json:"area"` + Save bool `json:"save"` + Name string `json:"name"` + Language string `json:"language"` +} + +// SearchResult is one page of a search. +type SearchResult struct { + Search *models.LeadSearch `json:"search"` + Leads []models.Lead `json:"leads"` + Found int `json:"found"` + OutsideArea int `json:"outside_area"` + CreditsCharged int `json:"credits_charged"` +} + +// Search runs a provider search over an area and stores what it returns. +func (s *Service) Search(ctx context.Context, orgID, userID uuid.UUID, req SearchRequest) (*SearchResult, error) { + var search *models.LeadSearch + if req.SearchID != nil { + got, err := s.Repo.GetSearch(ctx, orgID, *req.SearchID) + if err != nil { + return nil, err + } + if got == nil { + return nil, errx.New(errx.NotFound, "search not found") + } + // A search with no page recorded fetches its first page again. + if got.NextCursor == "" && got.PagesFetched > 0 { + return nil, errx.NewWithIdentifier(errx.BadRequest, "lead_search_exhausted", "This search has no more results") + } + search = got + } else { + var err error + if search, err = s.newSearch(orgID, userID, req); err != nil { + return nil, err + } + } + var category *Category + if search.Category != "" { + category = CategoryByID(search.Category) + } + provider, keySource, err := s.resolve(ctx, orgID, search.Provider) + if err != nil { + return nil, err + } + if search.PagesFetched >= providerMeta[search.Provider].MaxPages { + return nil, errx.NewWithIdentifier(errx.BadRequest, "lead_search_exhausted", "This search has no more results") + } + + charged, chargeKey := 0, "" + if keySource == "instance" && s.metered() { + chargeKey = fmt.Sprintf("lead_search:%s:%d", search.ID, search.PagesFetched) + if _, err := s.Credits.Charge(ctx, orgID, credits.CostLeadSearchPage, "lead_search", chargeKey); err != nil { + return nil, creditErr(err) + } + charged = credits.CostLeadSearchPage + } + pctx, cancel := context.WithTimeout(ctx, searchTimeout) + defer cancel() + page, err := provider.Search(pctx, Query{ + Text: search.Query, Category: category, Area: search.Area, Cursor: search.NextCursor, + Limit: providerMeta[search.Provider].PageSize, Language: req.Language, + }) + refund := func() { + if chargeKey == "" { + return + } + if _, rerr := s.Credits.RefundCharge(context.WithoutCancel(ctx), orgID, chargeKey, "lead_search_refund"); rerr != nil { + log.Warn().Err(rerr).Msg("leadfinder: could not refund a failed search") + } + } + if err != nil { + refund() + return nil, providerErr(search.Provider, err) + } + // A search is kept once its source answered, so a failed one leaves nothing behind. + if req.SearchID == nil { + if err := s.Repo.CreateSearch(ctx, search); err != nil { + refund() + return nil, err + } + } + + res := &SearchResult{Search: search, CreditsCharged: charged} + keep := make([]models.Lead, 0, len(page.Leads)) + seen := map[string]bool{} + for _, l := range page.Leads { + if l.ExternalID == "" || seen[l.ExternalID] { + continue + } + seen[l.ExternalID] = true + if !Contains(search.Area, models.LatLng{Lat: l.Latitude, Lng: l.Longitude}) { + res.OutsideArea++ + continue + } + keep = append(keep, sanitizeLead(l)) + } + ids, err := s.Repo.UpsertLeads(ctx, orgID, &search.ID, keep) + if err != nil { + return nil, err + } + search.PagesFetched++ + search.NextCursor = page.NextCursor + if search.PagesFetched >= providerMeta[search.Provider].MaxPages { + search.NextCursor = "" + } + if err := s.Repo.RecordSearchPage(ctx, search); err != nil { + return nil, err + } + search.HasMore = search.NextCursor != "" + res.Found = len(ids) + if res.Leads, err = s.Repo.LeadsByIDs(ctx, orgID, ids); err != nil { + return nil, err + } + return res, nil +} + +func (s *Service) newSearch(orgID, userID uuid.UUID, req SearchRequest) (*models.LeadSearch, error) { + if req.Provider == "" { + req.Provider = models.LeadProviderOSM + } else if !req.Provider.Valid() { + return nil, errx.New(errx.BadRequest, "unknown lead provider") + } + req.Query = strings.TrimSpace(req.Query) + if len([]rune(req.Query)) > 120 { + return nil, errx.New(errx.BadRequest, "the search is too long; keep it under 120 characters") + } + if req.Category != "" && CategoryByID(req.Category) == nil { + return nil, errx.New(errx.BadRequest, "unknown category") + } + if req.Query == "" && req.Category == "" { + return nil, errx.NewWithIdentifier(errx.BadRequest, "lead_search_empty", "Pick a category or type what to look for") + } + area, err := NormalizeArea(req.Area) + if err != nil { + return nil, errx.NewWithIdentifier(errx.BadRequest, "lead_search_area", err.Error()) + } + name := strings.TrimSpace(req.Name) + if name == "" { + name = searchName(req.Query, req.Category, req.LocationLabel) + } + uid := userID + return &models.LeadSearch{ + ID: uuid.New(), + OrganizationID: orgID, + CreatedByUserID: &uid, + Name: truncate(name, 120), + Provider: req.Provider, + Query: req.Query, + Category: req.Category, + LocationLabel: truncate(strings.TrimSpace(req.LocationLabel), 200), + Area: area, + Saved: req.Save, + }, nil +} + +func searchName(query, category, location string) string { + what := query + if c := CategoryByID(category); c != nil { + what = strings.TrimSpace(c.Label + " " + query) + } + if location = strings.TrimSpace(location); location != "" { + return what + " in " + location + } + return what +} + +// sanitizeLead bounds every free-text field a provider sent. +func sanitizeLead(l models.Lead) models.Lead { + l.Name = truncate(l.Name, 300) + l.Category = truncate(l.Category, 120) + cats := make([]string, 0, len(l.Categories)) + seenCat := map[string]bool{} + for _, c := range l.Categories { + c = truncate(strings.TrimSpace(c), 120) + if c != "" && !seenCat[strings.ToLower(c)] && len(cats) < 12 { + seenCat[strings.ToLower(c)] = true + cats = append(cats, c) + } + } + l.Categories = cats + l.Address = truncate(l.Address, 500) + l.Street, l.City, l.Region = truncate(l.Street, 200), truncate(l.City, 120), truncate(l.Region, 120) + l.Postcode, l.Country = truncate(l.Postcode, 32), truncate(l.Country, 80) + l.Phone = truncate(l.Phone, 64) + l.Website, l.MapsURL = truncate(l.Website, 1000), truncate(l.MapsURL, 1000) + l.Description = truncate(l.Description, 2000) + l.Chain = truncate(l.Chain, 200) + if len(l.Hours) > 14 { + l.Hours = l.Hours[:14] + } + for i := range l.Hours { + l.Hours[i] = truncate(l.Hours[i], 200) + } + return l +} + +func truncate(s string, n int) string { + r := []rune(s) + if len(r) <= n { + return s + } + return string(r[:n]) +} + +func creditErr(err error) error { + switch { + case errors.Is(err, credits.ErrInsufficientCredits): + return errx.NewWithIdentifier(errx.PaymentRequired, "insufficient_credits", "Not enough credits. Top up under Billing to keep going.") + case errors.Is(err, credits.ErrCapExceeded): + return errx.NewWithIdentifier(errx.TooManyRequests, "usage_cap_exceeded", "The workspace reached its credit spend limit for now.") + } + return err +} + +func providerErr(id models.LeadProvider, err error) error { + name := providerMeta[id].Name + switch { + case errors.Is(err, ErrProviderKey): + return errx.NewWithIdentifier(errx.BadRequest, "lead_provider_key", name+" refused the API key. Check it under Integrations.") + case errors.Is(err, ErrProviderQuota): + return errx.NewWithIdentifier(errx.TooManyRequests, "lead_provider_quota", name+" is rate limiting or out of quota. Try again later.") + case errors.Is(err, ErrAreaTooLarge): + return errx.NewWithIdentifier(errx.BadRequest, "lead_search_area", "Zoom in: the area is too large to search at once.") + case errors.Is(err, context.DeadlineExceeded): + return errx.NewWithIdentifier(errx.ServiceUnavailable, "lead_provider_unavailable", name+" took too long. Try a smaller area.") + } + log.Warn().Err(err).Str("provider", name).Msg("leadfinder: provider search failed") + return errx.NewWithIdentifier(errx.ServiceUnavailable, "lead_provider_unavailable", name+" could not be reached. Try again shortly.") +} + +// --- leads ------------------------------------------------------------------ + +// List returns a page of leads and how many match. +func (s *Service) List(ctx context.Context, orgID uuid.UUID, f *models.LeadFilter, sort models.LeadSort, limit, offset int) ([]models.Lead, int64, error) { + return s.Repo.ListLeads(ctx, orgID, f, sort, limit, offset) +} + +// Points returns the pins for the map. +func (s *Service) Points(ctx context.Context, orgID uuid.UUID, f *models.LeadFilter) ([]repository.LeadPoint, error) { + return s.Repo.LeadPoints(ctx, orgID, f, PointsCap) +} + +// Facets returns the filter values for the scope. +func (s *Service) Facets(ctx context.Context, orgID uuid.UUID, f *models.LeadFilter) (*repository.LeadFacets, error) { + return s.Repo.LeadFacets(ctx, orgID, f) +} + +// Get returns one lead. +func (s *Service) Get(ctx context.Context, orgID, id uuid.UUID) (*models.Lead, error) { + l, err := s.Repo.GetLead(ctx, orgID, id) + if err != nil { + return nil, err + } + if l == nil { + return nil, errx.New(errx.NotFound, "lead not found") + } + people, err := s.Repo.PeopleForLeads(ctx, orgID, []uuid.UUID{id}) + if err != nil { + return nil, err + } + l.People = people[id] + if l.People == nil { + l.People = []models.LeadPerson{} + } + return l, nil +} + +// Resolve turns a selection into lead ids within the cap. +func (s *Service) Resolve(ctx context.Context, orgID uuid.UUID, sel *models.LeadSelection) ([]uuid.UUID, error) { + if sel == nil || (!sel.All && len(sel.LeadIDs) == 0) { + return nil, errx.New(errx.BadRequest, "select at least one lead") + } + if !sel.All && len(sel.LeadIDs) > SelectionCap { + return nil, errx.NewWithIdentifier(errx.BadRequest, "lead_selection_too_large", "Select at most 5,000 leads at a time") + } + ids, err := s.Repo.ResolveSelection(ctx, orgID, sel, SelectionCap) + if err != nil { + return nil, err + } + if len(ids) == 0 { + return nil, errx.New(errx.NotFound, "none of the selected leads were found") + } + return ids, nil +} + +// Patch edits one or many leads. +func (s *Service) Patch(ctx context.Context, orgID uuid.UUID, ids []uuid.UUID, p *models.LeadPatch) (int64, error) { + if p.Status != nil && !p.Status.Valid() { + return 0, errx.New(errx.BadRequest, "unknown lead status") + } + if p.Notes != nil && len([]rune(*p.Notes)) > 5000 { + return 0, errx.New(errx.BadRequest, "notes are limited to 5,000 characters") + } + clean := func(tags []string) ([]string, error) { + out := make([]string, 0, len(tags)) + for _, t := range tags { + t = strings.TrimSpace(t) + if t == "" { + continue + } + if len([]rune(t)) > 40 { + return nil, errx.New(errx.BadRequest, "a tag is limited to 40 characters") + } + out = append(out, t) + } + if len(out) > 20 { + return nil, errx.New(errx.BadRequest, "a lead takes at most 20 tags") + } + return out, nil + } + var err error + if p.Tags != nil { + t, cerr := clean(*p.Tags) + if cerr != nil { + return 0, cerr + } + p.Tags = &t + } + if p.AddTags, err = clean(p.AddTags); err != nil { + return 0, err + } + if p.RemoveTags, err = clean(p.RemoveTags); err != nil { + return 0, err + } + return s.Repo.PatchLeads(ctx, orgID, ids, p) +} + +// Delete removes leads. Contacts made from them stay. +func (s *Service) Delete(ctx context.Context, orgID uuid.UUID, ids []uuid.UUID) (int64, error) { + return s.Repo.DeleteLeads(ctx, orgID, ids) +} + +// --- searches --------------------------------------------------------------- + +// Searches lists recent and saved searches. +func (s *Service) Searches(ctx context.Context, orgID uuid.UUID, savedOnly bool) ([]models.LeadSearch, error) { + return s.Repo.ListSearches(ctx, orgID, savedOnly, 50) +} + +// UpdateSearch renames a search or saves it. +func (s *Service) UpdateSearch(ctx context.Context, orgID, id uuid.UUID, name *string, saved *bool) (*models.LeadSearch, error) { + if name != nil { + n := strings.TrimSpace(*name) + if n == "" || len([]rune(n)) > 120 { + return nil, errx.New(errx.BadRequest, "a search name is 1 to 120 characters") + } + name = &n + } + out, err := s.Repo.UpdateSearch(ctx, orgID, id, name, saved) + if errors.Is(err, repository.ErrLeadSearchNotFound) { + return nil, errx.New(errx.NotFound, "search not found") + } + return out, err +} + +// DeleteSearch removes a search. Its leads stay. +func (s *Service) DeleteSearch(ctx context.Context, orgID, id uuid.UUID) error { + ok, err := s.Repo.DeleteSearch(ctx, orgID, id) + if err != nil { + return err + } + if !ok { + return errx.New(errx.NotFound, "search not found") + } + return nil +} diff --git a/internal/app/leadfinder/sitefind.go b/internal/app/leadfinder/sitefind.go new file mode 100644 index 000000000..6bf151010 --- /dev/null +++ b/internal/app/leadfinder/sitefind.go @@ -0,0 +1,199 @@ +package leadfinder + +import ( + "context" + "net" + "net/url" + "regexp" + "strings" + "sync" + "time" + + "github.com/warmbly/warmbly/internal/models" +) + +const ( + siteFindMaxCandidates = 8 + siteFindMaxReads = 3 + siteFindLookupTimeout = 3 * time.Second + siteFindTimeout = 20 * time.Second +) + +// legalWords say what kind of company a name is, never what its domain is. +var legalWords = map[string]bool{ + "llc": true, "inc": true, "ltd": true, "limited": true, "gmbh": true, "co": true, "corp": true, "pllc": true, "pc": true, + "pa": true, "plc": true, "kft": true, "bt": true, "zrt": true, "sarl": true, "sas": true, "srl": true, "spa": true, "bv": true, + "ag": true, "kg": true, "ohg": true, "ug": true, "dds": true, "dmd": true, "md": true, "cpa": true, "esq": true, +} + +// countryTLDs are the endings a business in that country is most likely on, before .com. +var countryTLDs = map[string][]string{ + "GB": {"co.uk"}, "UK": {"co.uk"}, "AU": {"com.au"}, "NZ": {"co.nz"}, "BR": {"com.br"}, "MX": {"com.mx"}, + "AR": {"com.ar"}, "ZA": {"co.za"}, "JP": {"co.jp"}, "IN": {"in", "co.in"}, +} + +var nonAlnum = regexp.MustCompile(`[^a-z0-9]+`) + +// nameTokens folds a business name to the words a domain is built from. +func nameTokens(name string) []string { + s := strings.ReplaceAll(asciiFold(name), "&", " and ") + var out []string + for i, w := range strings.Fields(nonAlnum.ReplaceAllString(s, " ")) { + if legalWords[w] || (i == 0 && w == "the") { + continue + } + out = append(out, w) + } + return out +} + +// folded is text reduced to lowercase ASCII words separated by single spaces. +func folded(s string) string { + return strings.Join(strings.Fields(nonAlnum.ReplaceAllString(asciiFold(s), " ")), " ") +} + +// siteCandidates are the domains a business with this name most likely owns, best first. +func siteCandidates(l *models.Lead) []string { + tokens := nameTokens(l.Name) + if len(tokens) == 0 { + return nil + } + var labels []string + add := func(s string) { + if len(s) >= 4 && len(s) <= 40 && !containsStr(labels, s) { + labels = append(labels, s) + } + } + add(strings.Join(tokens, "")) + if len(tokens) > 1 { + add(strings.Join(tokens, "-")) + } + var plain []string + for _, t := range tokens { + if t != "and" && t != "of" { + plain = append(plain, t) + } + } + add(strings.Join(plain, "")) + if city := strings.ReplaceAll(folded(l.City), " ", ""); city != "" && len(tokens) <= 3 { + add(strings.Join(tokens, "") + city) + } + + country := strings.ToUpper(strings.TrimSpace(l.Country)) + tlds := append([]string(nil), countryTLDs[country]...) + if len(tlds) == 0 && len(country) == 2 && country != "US" { + tlds = []string{strings.ToLower(country)} + } + tlds = append(tlds, "com") + + var out []string + for _, tld := range tlds { + for _, label := range labels { + if len(out) < siteFindMaxCandidates { + out = append(out, label+"."+tld) + } + } + } + return out +} + +// FindWebsite works out the site of a business whose listing has none. A +// candidate counts only when its home page carries the business's phone +// number, or its full name together with its town, street or postcode. +func (c *Crawler) FindWebsite(ctx context.Context, l *models.Lead) (string, string) { + ctx, cancel := context.WithTimeout(ctx, siteFindTimeout) + defer cancel() + cands := siteCandidates(l) + live := make([]bool, len(cands)) + var wg sync.WaitGroup + for i, host := range cands { + wg.Add(1) + go func(i int, host string) { + defer wg.Done() + lctx, cancel := context.WithTimeout(ctx, siteFindLookupTimeout) + defer cancel() + addrs, err := c.lookup(lctx, host) + live[i] = err == nil && len(addrs) > 0 + }(i, host) + } + wg.Wait() + + reads := 0 + for i, host := range cands { + if !live[i] || reads >= siteFindMaxReads || ctx.Err() != nil { + continue + } + reads++ + start := &url.URL{Scheme: "https", Host: host, Path: "/"} + rules := c.robots(ctx, start) + p, err := c.fetch(ctx, start.String(), rules) + if err != nil { + start.Scheme = "http" + p, err = c.fetch(ctx, start.String(), c.robots(ctx, start)) + } + if err != nil || !confirmsBusiness(p, l) { + continue + } + home := url.URL{Scheme: p.url.Scheme, Host: p.url.Host, Path: "/"} + if website, domain := NormalizeWebsite(home.String()); website != "" { + return website, domain + } + } + return "", "" +} + +// confirmsBusiness says whether a page is the business's own. +func confirmsBusiness(p *page, l *models.Lead) bool { + if want := phoneTail(l.Phone); want != "" { + for _, ph := range p.phones { + if phoneTail(ph) == want { + return true + } + } + for _, seg := range p.segments { + for _, run := range phoneRun.FindAllString(seg, -1) { + if phoneTail(run) == want { + return true + } + } + } + } + name := strings.Join(nameTokens(l.Name), " ") + if len(name) < 4 { + return false + } + text := " " + folded(p.title+" "+strings.Join(p.segments, " ")) + " " + if !strings.Contains(text, " "+name+" ") { + return false + } + for _, place := range []string{l.City, l.Street, l.Postcode} { + if f := folded(place); len(f) >= 3 && strings.Contains(text, " "+f+" ") { + return true + } + } + return false +} + +var phoneRun = regexp.MustCompile(`\+?\d[\d\s().\-/]{6,}\d`) + +// phoneTail is the part of a number that stays the same however it is +// written: its last nine digits, or all of a seven or eight digit one. +func phoneTail(s string) string { + d := strings.Map(func(r rune) rune { + if r >= '0' && r <= '9' { + return r + } + return -1 + }, s) + switch { + case len(d) >= 9: + return d[len(d)-9:] + case len(d) >= 7: + return d + } + return "" +} + +func defaultLookup(ctx context.Context, host string) ([]string, error) { + return net.DefaultResolver.LookupHost(ctx, host) +} diff --git a/internal/app/leadfinder/sitefind_test.go b/internal/app/leadfinder/sitefind_test.go new file mode 100644 index 000000000..5341ee4ed --- /dev/null +++ b/internal/app/leadfinder/sitefind_test.go @@ -0,0 +1,90 @@ +package leadfinder + +import ( + "context" + "net" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/warmbly/warmbly/internal/models" +) + +func TestSiteCandidates(t *testing.T) { + got := siteCandidates(&models.Lead{Name: "Moon Creek Dental, PLLC", City: "Boise", Country: "US"}) + want := []string{"mooncreekdental.com", "moon-creek-dental.com", "mooncreekdentalboise.com"} + if strings.Join(got, " ") != strings.Join(want, " ") { + t.Fatalf("candidates = %v, want %v", got, want) + } + + de := siteCandidates(&models.Lead{Name: "Zahnarztpraxis Müller & Söhne GmbH", Country: "DE"}) + if len(de) == 0 || de[0] != "zahnarztpraxismullerandsohne.de" || !containsStr(de, "zahnarztpraxismullersohne.com") { + t.Fatalf("german candidates = %v", de) + } + if uk := siteCandidates(&models.Lead{Name: "The Bakehouse", Country: "GB"}); len(uk) == 0 || uk[0] != "bakehouse.co.uk" { + t.Fatalf("uk candidates = %v", uk) + } + if len(siteCandidates(&models.Lead{Name: "LLC"})) != 0 { + t.Fatal("a name of only legal words has no domain") + } +} + +func TestConfirmsBusiness(t *testing.T) { + lead := &models.Lead{Name: "Moon Creek Dental", City: "Boise", Street: "Overland Road", Phone: "+1 208 939 7053"} + cases := []struct { + name string + html string + want bool + }{ + {"phone in text", `

Call us (208) 939-7053

`, true}, + {"phone link", `Call`, true}, + {"name and city", `Moon Creek Dental | Boise dentist`, true}, + {"name elsewhere", `Moon Creek Dental

Serving Portland, Oregon

`, false}, + {"parked", `

mooncreekdental.com is for sale

Boise

`, false}, + {"other number", `

Call (208) 555-0199. Boise.

`, false}, + } + for _, c := range cases { + if got := confirmsBusiness(parsePage(c.html), lead); got != c.want { + t.Errorf("%s: confirms = %v, want %v", c.name, got, c.want) + } + } +} + +func TestFindWebsite(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/robots.txt" { + http.NotFound(w, r) + return + } + w.Header().Set("Content-Type", "text/html") + if strings.HasPrefix(r.Host, "moon-creek-dental.com") { + _, _ = w.Write([]byte(`

Moon Creek Dental, call 208-939-7053

`)) + return + } + _, _ = w.Write([]byte(`

This domain is for sale

`)) + })) + defer srv.Close() + + c := NewCrawler("test") + c.client = &http.Client{Timeout: 5 * time.Second, Transport: &http.Transport{ + DialContext: func(ctx context.Context, network, _ string) (net.Conn, error) { + return (&net.Dialer{}).DialContext(ctx, network, srv.Listener.Addr().String()) + }, + }} + c.lookup = func(_ context.Context, host string) ([]string, error) { + if host == "mooncreekdental.com" || host == "moon-creek-dental.com" { + return []string{"192.0.2.1"}, nil + } + return nil, &net.DNSError{Err: "no such host", Name: host, IsNotFound: true} + } + + website, domain := c.FindWebsite(context.Background(), &models.Lead{Name: "Moon Creek Dental", City: "Boise", Country: "US", Phone: "+1 208 939 7053"}) + if website != "http://moon-creek-dental.com/" || domain != "moon-creek-dental.com" { + t.Fatalf("found %q %q", website, domain) + } + if w, _ := c.FindWebsite(context.Background(), &models.Lead{Name: "Nobody Here", Country: "US"}); w != "" { + t.Fatalf("found %q for a business with no site", w) + } +} diff --git a/internal/app/orgtransfer/spec.go b/internal/app/orgtransfer/spec.go index 5c2403b7c..3e9cb166e 100644 --- a/internal/app/orgtransfer/spec.go +++ b/internal/app/orgtransfer/spec.go @@ -385,6 +385,27 @@ var Tables = []Table{ Scope: scopeOrg, Note: "Column mappings the workspace confirmed for its contact imports, keyed by header set, so the same export maps itself on the destination too.", }, + { + Name: "lead_searches", Group: models.OrgDataGroupContacts, + Scope: scopeOrg, + ResetOnImport: []string{"next_cursor", "pages_fetched"}, + Note: "Lead finder searches and saved searches. A provider's paging token only means something to the session that fetched it, so a search resumes from its first page.", + }, + { + Name: "leads", Group: models.OrgDataGroupContacts, + Scope: scopeOrg, + Note: "Businesses found with the lead finder, with what reading their websites found and the contact each became.", + }, + { + Name: "lead_search_hits", Group: models.OrgDataGroupContacts, + Scope: `search_id IN (SELECT id FROM lead_searches WHERE organization_id = $1)`, + Note: "Which search found each lead, so a saved search reopens with its results.", + }, + { + Name: "lead_people", Group: models.OrgDataGroupContacts, + Scope: scopeOrg, + Note: "People found at each lead's business, with the address found or worked out for them and the contact each became.", + }, { Name: "contact_categories", Group: models.OrgDataGroupContacts, Scope: `contact_id IN ` + orgContacts, @@ -1083,6 +1104,7 @@ var ExcludedTables = map[string]string{ "crm_sync_jobs": "The outbox of pending CRM writes on this instance; the destination's own events feed its outbox.", "crm_sync_cursors": "Pull checkpoints for this instance; the destination starts its own pull.", "apollo_enrichment_runs": "The progress of enrichment requests run on this instance. What they found is already on the contacts, which travel.", + "lead_enrichment_runs": "The progress of website reads run on this instance. What they found is already on the leads, which travel.", "salesforce_record_links": "Which Salesforce record each contact is, with a cached copy of it. The destination links contacts again by address the first time it syncs or shows them, and reads the record fresh.", "salesforce_activity_queue": "Activity waiting to be logged in Salesforce, and the recent outcome of what was. What was logged is already in Salesforce; what was waiting belongs to this instance's drain.", "salesforce_sync_state": "Where this instance's pull loop got to in each Salesforce org, and the API calls it counted today. The destination starts its own cursor when the connection first syncs.", diff --git a/internal/infrastructure/db/migrations/000363_lead_finder.down.sql b/internal/infrastructure/db/migrations/000363_lead_finder.down.sql new file mode 100644 index 000000000..23ea93447 --- /dev/null +++ b/internal/infrastructure/db/migrations/000363_lead_finder.down.sql @@ -0,0 +1,10 @@ +DROP TABLE IF EXISTS lead_people; +DROP TABLE IF EXISTS lead_enrichment_runs; +DROP TABLE IF EXISTS lead_search_hits; +DROP TABLE IF EXISTS leads; +DROP TABLE IF EXISTS lead_searches; + +ALTER TABLE public.contacts DROP CONSTRAINT contacts_source_check; +ALTER TABLE public.contacts + ADD CONSTRAINT contacts_source_check + CHECK (source IN ('unknown', 'manual', 'campaign', 'import', 'sheet_sync', 'api', 'ai_assistant', 'form', 'automation', 'crm_sync', 'apollo', 'clay')) NOT VALID; diff --git a/internal/infrastructure/db/migrations/000363_lead_finder.up.sql b/internal/infrastructure/db/migrations/000363_lead_finder.up.sql new file mode 100644 index 000000000..6d532e3b3 --- /dev/null +++ b/internal/infrastructure/db/migrations/000363_lead_finder.up.sql @@ -0,0 +1,146 @@ +-- Lead finder: local businesses found on a map through a pluggable place +-- provider, enriched from their own websites, and turned into contacts. + +ALTER TABLE public.contacts DROP CONSTRAINT contacts_source_check; +ALTER TABLE public.contacts + ADD CONSTRAINT contacts_source_check + CHECK (source IN ('unknown', 'manual', 'campaign', 'import', 'sheet_sync', 'api', 'ai_assistant', 'form', 'automation', 'crm_sync', 'apollo', 'clay', 'lead_finder')) NOT VALID; + +-- A search someone ran: what, where and through which provider. +CREATE TABLE lead_searches ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + organization_id uuid NOT NULL REFERENCES organizations (id) ON DELETE CASCADE, + created_by_user_id uuid REFERENCES users (id) ON DELETE SET NULL, + name text NOT NULL DEFAULT '', + provider text NOT NULL CHECK (provider IN ('osm', 'google_places', 'foursquare', 'outscraper')), + query text NOT NULL DEFAULT '', + category text NOT NULL DEFAULT '', + location_label text NOT NULL DEFAULT '', + area jsonb NOT NULL, + saved boolean NOT NULL DEFAULT false, + result_count integer NOT NULL DEFAULT 0, + pages_fetched integer NOT NULL DEFAULT 0, + next_cursor text NOT NULL DEFAULT '', + last_run_at timestamptz NOT NULL DEFAULT NOW(), + created_at timestamptz NOT NULL DEFAULT NOW(), + updated_at timestamptz NOT NULL DEFAULT NOW() +); + +CREATE INDEX idx_lead_searches_org ON lead_searches (organization_id, last_run_at DESC); + +-- One business, once per workspace and provider record. +CREATE TABLE leads ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + organization_id uuid NOT NULL REFERENCES organizations (id) ON DELETE CASCADE, + provider text NOT NULL CHECK (provider IN ('osm', 'google_places', 'foursquare', 'outscraper')), + external_id text NOT NULL CHECK (external_id <> ''), + name text NOT NULL DEFAULT '', + category text NOT NULL DEFAULT '', + categories text[] NOT NULL DEFAULT '{}', + address text NOT NULL DEFAULT '', + street text NOT NULL DEFAULT '', + city text NOT NULL DEFAULT '', + region text NOT NULL DEFAULT '', + postcode text NOT NULL DEFAULT '', + country text NOT NULL DEFAULT '', + latitude double precision NOT NULL, + longitude double precision NOT NULL, + phone text NOT NULL DEFAULT '', + website text NOT NULL DEFAULT '', + domain text NOT NULL DEFAULT '', + email text NOT NULL DEFAULT '', + emails jsonb NOT NULL DEFAULT '[]'::jsonb, + socials jsonb NOT NULL DEFAULT '{}'::jsonb, + rating double precision, + review_count integer, + price_level smallint, + hours jsonb NOT NULL DEFAULT '[]'::jsonb, + business_status text NOT NULL DEFAULT '', + maps_url text NOT NULL DEFAULT '', + description text NOT NULL DEFAULT '', + chain text NOT NULL DEFAULT '', + site jsonb NOT NULL DEFAULT '{}'::jsonb, + score smallint NOT NULL DEFAULT 0, + status text NOT NULL DEFAULT 'new' CHECK (status IN ('new', 'saved', 'contacted', 'dismissed')), + enrichment_status text NOT NULL DEFAULT 'none' CHECK (enrichment_status IN ('none', 'queued', 'done', 'no_website', 'failed')), + enriched_at timestamptz, + contact_id uuid REFERENCES contacts (id) ON DELETE SET NULL, + tags text[] NOT NULL DEFAULT '{}', + notes text NOT NULL DEFAULT '', + first_seen_at timestamptz NOT NULL DEFAULT NOW(), + last_seen_at timestamptz NOT NULL DEFAULT NOW(), + created_at timestamptz NOT NULL DEFAULT NOW(), + updated_at timestamptz NOT NULL DEFAULT NOW(), + UNIQUE (organization_id, provider, external_id) +); + +CREATE INDEX idx_leads_org_seen ON leads (organization_id, last_seen_at DESC, id DESC); +CREATE INDEX idx_leads_org_score ON leads (organization_id, score DESC, id DESC); +CREATE INDEX idx_leads_org_geo ON leads (organization_id, latitude, longitude); +CREATE INDEX idx_leads_contact ON leads (contact_id) WHERE contact_id IS NOT NULL; + +-- Which searches returned a lead, so a saved search reopens with its results. +CREATE TABLE lead_search_hits ( + search_id uuid NOT NULL REFERENCES lead_searches (id) ON DELETE CASCADE, + lead_id uuid NOT NULL REFERENCES leads (id) ON DELETE CASCADE, + seen_at timestamptz NOT NULL DEFAULT NOW(), + PRIMARY KEY (search_id, lead_id) +); + +CREATE INDEX idx_lead_search_hits_lead ON lead_search_hits (lead_id); + +-- One request to read a set of leads' websites for emails and socials. Runs in +-- the background; the row is its progress and outcome. +CREATE TABLE lead_enrichment_runs ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + organization_id uuid NOT NULL REFERENCES organizations (id) ON DELETE CASCADE, + requested_by_user_id uuid REFERENCES users (id) ON DELETE SET NULL, + lead_ids uuid[] NOT NULL, + verify boolean NOT NULL DEFAULT true, + people boolean NOT NULL DEFAULT true, + status text NOT NULL DEFAULT 'queued' CHECK (status IN ('queued', 'running', 'done', 'error')), + total integer NOT NULL DEFAULT 0, + processed integer NOT NULL DEFAULT 0, + emails_found integer NOT NULL DEFAULT 0, + people_found integer NOT NULL DEFAULT 0, + no_website integer NOT NULL DEFAULT 0, + failed integer NOT NULL DEFAULT 0, + credits_consumed integer NOT NULL DEFAULT 0, + last_error text NOT NULL DEFAULT '', + started_at timestamptz, + finished_at timestamptz, + created_at timestamptz NOT NULL DEFAULT NOW(), + updated_at timestamptz NOT NULL DEFAULT NOW() +); + +CREATE INDEX idx_lead_enrichment_runs_org ON lead_enrichment_runs (organization_id, created_at DESC); +CREATE INDEX idx_lead_enrichment_runs_open ON lead_enrichment_runs (status, updated_at) WHERE status IN ('queued', 'running'); + +-- People who work at a lead's business: read off its website or typed in by +-- hand, with the address found for them or worked out from the domain's pattern. +CREATE TABLE lead_people ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + organization_id uuid NOT NULL REFERENCES organizations (id) ON DELETE CASCADE, + lead_id uuid NOT NULL REFERENCES leads (id) ON DELETE CASCADE, + name text NOT NULL CHECK (name <> ''), + name_key text NOT NULL CHECK (name_key <> ''), + first_name text NOT NULL DEFAULT '', + last_name text NOT NULL DEFAULT '', + title text NOT NULL DEFAULT '', + seniority text NOT NULL DEFAULT 'staff' CHECK (seniority IN ('owner', 'executive', 'manager', 'staff')), + email text NOT NULL DEFAULT '', + email_source text NOT NULL DEFAULT '' CHECK (email_source IN ('', 'website', 'pattern', 'manual')), + email_status text NOT NULL DEFAULT '', + email_confidence smallint NOT NULL DEFAULT 0 CHECK (email_confidence BETWEEN 0 AND 100), + linkedin_url text NOT NULL DEFAULT '', + phone text NOT NULL DEFAULT '', + source text NOT NULL CHECK (source IN ('schema', 'page', 'imprint', 'email', 'linkedin', 'manual')), + source_url text NOT NULL DEFAULT '', + contact_id uuid REFERENCES contacts (id) ON DELETE SET NULL, + created_at timestamptz NOT NULL DEFAULT NOW(), + updated_at timestamptz NOT NULL DEFAULT NOW(), + UNIQUE (lead_id, name_key) +); + +CREATE INDEX idx_lead_people_org_lead ON lead_people (organization_id, lead_id); +CREATE INDEX idx_lead_people_contact ON lead_people (contact_id) WHERE contact_id IS NOT NULL; diff --git a/internal/models/audit.go b/internal/models/audit.go index 0f090ee25..24747b97d 100644 --- a/internal/models/audit.go +++ b/internal/models/audit.go @@ -110,6 +110,8 @@ const ( AuditEntityTeam AuditEntityType = "team" AuditEntityAutomation AuditEntityType = "automation" AuditEntityLeadSyncSource AuditEntityType = "lead_sync_source" + AuditEntityLead AuditEntityType = "lead" + AuditEntityLeadSearch AuditEntityType = "lead_search" AuditEntityMeeting AuditEntityType = "meeting" // Workspace archives (export/import for moving between instances). diff --git a/internal/models/contact.go b/internal/models/contact.go index 6a3b0447f..50f69bbad 100644 --- a/internal/models/contact.go +++ b/internal/models/contact.go @@ -853,6 +853,9 @@ const ( // ContactSourceClay is a contact a Clay table sent in; the detail names the // connection. ContactSourceClay ContactSource = "clay" + // ContactSourceLeadFinder is a business found on the lead finder map; the + // detail names the search. + ContactSourceLeadFinder ContactSource = "lead_finder" ) // Valid reports whether the value is one the database accepts. @@ -860,7 +863,8 @@ func (s ContactSource) Valid() bool { switch s { case ContactSourceUnknown, ContactSourceManual, ContactSourceCampaign, ContactSourceImport, ContactSourceSheetSync, ContactSourceAPI, ContactSourceAIAssistant, ContactSourceForm, - ContactSourceAutomation, ContactSourceCRMSync, ContactSourceApollo, ContactSourceClay: + ContactSourceAutomation, ContactSourceCRMSync, ContactSourceApollo, ContactSourceClay, + ContactSourceLeadFinder: return true } return false diff --git a/internal/models/integration.go b/internal/models/integration.go index 319d35dc5..c27d982e6 100644 --- a/internal/models/integration.go +++ b/internal/models/integration.go @@ -38,6 +38,11 @@ const ( IntegrationApollo IntegrationProvider = "apollo" IntegrationClay IntegrationProvider = "clay" + // Lead finder place providers; a connection holds the workspace's own key. + IntegrationGooglePlaces IntegrationProvider = "google_places" + IntegrationFoursquare IntegrationProvider = "foursquare" + IntegrationOutscraper IntegrationProvider = "outscraper" + // Verification IntegrationMillionVerifier IntegrationProvider = "millionverifier" IntegrationCleanMyList IntegrationProvider = "cleanmylist" @@ -64,6 +69,9 @@ var AllIntegrationProviders = []IntegrationProvider{ IntegrationGoogleSheets, IntegrationApollo, IntegrationClay, + IntegrationGooglePlaces, + IntegrationFoursquare, + IntegrationOutscraper, IntegrationMillionVerifier, IntegrationCleanMyList, } diff --git a/internal/models/lead_finder.go b/internal/models/lead_finder.go new file mode 100644 index 000000000..fd6f60120 --- /dev/null +++ b/internal/models/lead_finder.go @@ -0,0 +1,365 @@ +package models + +import ( + "time" + + "github.com/google/uuid" +) + +// LeadProvider is where a lead's business record came from. Mirrors the CHECK +// on leads.provider and lead_searches.provider. +type LeadProvider string + +const ( + // LeadProviderOSM is OpenStreetMap through an Overpass endpoint. Free, no key. + LeadProviderOSM LeadProvider = "osm" + // LeadProviderGooglePlaces is the Google Places API (New). + LeadProviderGooglePlaces LeadProvider = "google_places" + // LeadProviderFoursquare is the Foursquare Places API. + LeadProviderFoursquare LeadProvider = "foursquare" + // LeadProviderOutscraper is Outscraper's Google Maps search. + LeadProviderOutscraper LeadProvider = "outscraper" +) + +// LeadProviders lists every provider in the order the finder offers them. +var LeadProviders = []LeadProvider{LeadProviderOSM, LeadProviderGooglePlaces, LeadProviderFoursquare, LeadProviderOutscraper} + +// Valid reports whether the value is one the database accepts. +func (p LeadProvider) Valid() bool { + for _, v := range LeadProviders { + if p == v { + return true + } + } + return false +} + +// LeadStatus is where a lead stands in someone's prospecting. +type LeadStatus string + +const ( + LeadStatusNew LeadStatus = "new" + LeadStatusSaved LeadStatus = "saved" + LeadStatusContacted LeadStatus = "contacted" + LeadStatusDismissed LeadStatus = "dismissed" +) + +// Valid reports whether the value is one the database accepts. +func (s LeadStatus) Valid() bool { + switch s { + case LeadStatusNew, LeadStatusSaved, LeadStatusContacted, LeadStatusDismissed: + return true + } + return false +} + +// LeadEnrichmentStatus is how far reading a lead's website got. +type LeadEnrichmentStatus string + +const ( + LeadEnrichmentNone LeadEnrichmentStatus = "none" + LeadEnrichmentQueued LeadEnrichmentStatus = "queued" + LeadEnrichmentDone LeadEnrichmentStatus = "done" + LeadEnrichmentNoWebsite LeadEnrichmentStatus = "no_website" + LeadEnrichmentFailed LeadEnrichmentStatus = "failed" +) + +// Valid reports whether the value is one the database accepts. +func (s LeadEnrichmentStatus) Valid() bool { + switch s { + case LeadEnrichmentNone, LeadEnrichmentQueued, LeadEnrichmentDone, LeadEnrichmentNoWebsite, LeadEnrichmentFailed: + return true + } + return false +} + +// LatLng is one point on the map. +type LatLng struct { + Lat float64 `json:"lat"` + Lng float64 `json:"lng"` +} + +// LeadAreaKind is the shape a search covers. +type LeadAreaKind string + +const ( + LeadAreaBBox LeadAreaKind = "bbox" + LeadAreaCircle LeadAreaKind = "circle" + LeadAreaPolygon LeadAreaKind = "polygon" +) + +// LeadBounds is a south-west to north-east rectangle. +type LeadBounds struct { + South float64 `json:"south"` + West float64 `json:"west"` + North float64 `json:"north"` + East float64 `json:"east"` +} + +// LeadArea is the part of the map a search covers. Bounds is always set: for a +// circle or polygon it is the shape's bounding box. +type LeadArea struct { + Kind LeadAreaKind `json:"kind"` + Bounds LeadBounds `json:"bounds"` + Center *LatLng `json:"center,omitempty"` + RadiusM float64 `json:"radius_m,omitempty"` + Polygon []LatLng `json:"polygon,omitempty"` +} + +// LeadEmail is one address found for a lead and what checking it said. +type LeadEmail struct { + Email string `json:"email"` + // Source is "website" when read off the business's site, else the provider. + Source string `json:"source"` + URL string `json:"url,omitempty"` + DomainMatch bool `json:"domain_match"` + Status string `json:"status,omitempty"` + SubStatus string `json:"sub_status,omitempty"` +} + +// LeadSite is what reading a lead's website found besides addresses. +type LeadSite struct { + Reachable bool `json:"reachable"` + FinalURL string `json:"final_url,omitempty"` + HTTPS bool `json:"https"` + Title string `json:"title,omitempty"` + Description string `json:"description,omitempty"` + Platform string `json:"platform,omitempty"` + Signals []string `json:"signals,omitempty"` + Phones []string `json:"phones,omitempty"` + Pages int `json:"pages,omitempty"` + // EmailPattern is how the domain builds a person's address ("first.last"), + // learned from addresses found or a verified guess. + EmailPattern string `json:"email_pattern,omitempty"` + // AcceptsAll is set when the domain's mail server accepts any address, so a + // guessed address cannot be confirmed. + AcceptsAll bool `json:"accepts_all,omitempty"` + // FoundWebsite is set when the listing had no website and the finder + // confirmed one worked out from the business's name. + FoundWebsite bool `json:"found_website,omitempty"` + Error string `json:"error,omitempty"` + CheckedAt *time.Time `json:"checked_at,omitempty"` +} + +// Lead is one business in a workspace's lead finder. +type Lead struct { + ID uuid.UUID `json:"id"` + OrganizationID uuid.UUID `json:"-"` + Provider LeadProvider `json:"provider"` + ExternalID string `json:"external_id"` + Name string `json:"name"` + Category string `json:"category"` + Categories []string `json:"categories"` + Address string `json:"address"` + Street string `json:"street"` + City string `json:"city"` + Region string `json:"region"` + Postcode string `json:"postcode"` + Country string `json:"country"` + Latitude float64 `json:"latitude"` + Longitude float64 `json:"longitude"` + Phone string `json:"phone"` + Website string `json:"website"` + Domain string `json:"domain"` + Email string `json:"email"` + Emails []LeadEmail `json:"emails"` + Socials map[string]string `json:"socials"` + Rating *float64 `json:"rating"` + ReviewCount *int `json:"review_count"` + PriceLevel *int `json:"price_level"` + Hours []string `json:"hours"` + BusinessStatus string `json:"business_status"` + MapsURL string `json:"maps_url"` + Description string `json:"description"` + Chain string `json:"chain"` + Site LeadSite `json:"site"` + Score int `json:"score"` + Status LeadStatus `json:"status"` + EnrichmentStatus LeadEnrichmentStatus `json:"enrichment_status"` + EnrichedAt *time.Time `json:"enriched_at"` + ContactID *uuid.UUID `json:"contact_id"` + Tags []string `json:"tags"` + Notes string `json:"notes"` + PeopleCount int `json:"people_count"` + // People is loaded only where one lead is read in full. + People []LeadPerson `json:"people,omitempty"` + FirstSeenAt time.Time `json:"first_seen_at"` + LastSeenAt time.Time `json:"last_seen_at"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` +} + +// LeadSeniority places a person in their business. Mirrors the CHECK on +// lead_people.seniority. +type LeadSeniority string + +const ( + LeadSeniorityOwner LeadSeniority = "owner" + LeadSeniorityExecutive LeadSeniority = "executive" + LeadSeniorityManager LeadSeniority = "manager" + LeadSeniorityStaff LeadSeniority = "staff" +) + +// LeadPersonSource is where a person was found. Mirrors the CHECK on lead_people.source. +type LeadPersonSource string + +const ( + // LeadPersonSchema is structured data (schema.org Person) on the website. + LeadPersonSchema LeadPersonSource = "schema" + // LeadPersonPage is a name and role read off a team or about page. + LeadPersonPage LeadPersonSource = "page" + // LeadPersonImprint is a legal notice naming the owner or managing director. + LeadPersonImprint LeadPersonSource = "imprint" + // LeadPersonEmail is a personal address on the site whose owner was named. + LeadPersonEmail LeadPersonSource = "email" + // LeadPersonLinkedIn is a LinkedIn profile linked from the website. + LeadPersonLinkedIn LeadPersonSource = "linkedin" + // LeadPersonManual is someone a teammate typed in. + LeadPersonManual LeadPersonSource = "manual" +) + +// LeadEmailSource says how a person's address was arrived at. Mirrors the CHECK +// on lead_people.email_source. +type LeadEmailSource string + +const ( + LeadEmailNone LeadEmailSource = "" + // LeadEmailWebsite was published on the business's own site. + LeadEmailWebsite LeadEmailSource = "website" + // LeadEmailPattern was built from the name and the domain's address pattern. + LeadEmailPattern LeadEmailSource = "pattern" + // LeadEmailManual was typed in by a teammate. + LeadEmailManual LeadEmailSource = "manual" +) + +// LeadPersonStatusGuessed marks a pattern-built address nothing could confirm. +const LeadPersonStatusGuessed = "guessed" + +// LeadPerson is one person who works at a lead's business. +type LeadPerson struct { + ID uuid.UUID `json:"id"` + OrganizationID uuid.UUID `json:"-"` + LeadID uuid.UUID `json:"lead_id"` + Name string `json:"name"` + // NameKey is the folded "first last" two mentions of one person share. + NameKey string `json:"-"` + FirstName string `json:"first_name"` + LastName string `json:"last_name"` + Title string `json:"title"` + Seniority LeadSeniority `json:"seniority"` + Email string `json:"email"` + EmailSource LeadEmailSource `json:"email_source"` + EmailStatus string `json:"email_status"` + EmailConfidence int `json:"email_confidence"` + LinkedInURL string `json:"linkedin_url"` + Phone string `json:"phone"` + Source LeadPersonSource `json:"source"` + SourceURL string `json:"source_url"` + ContactID *uuid.UUID `json:"contact_id"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` +} + +// LeadSearch is one search someone ran on the lead finder map. +type LeadSearch struct { + ID uuid.UUID `json:"id"` + OrganizationID uuid.UUID `json:"-"` + CreatedByUserID *uuid.UUID `json:"created_by_user_id"` + Name string `json:"name"` + Provider LeadProvider `json:"provider"` + Query string `json:"query"` + Category string `json:"category"` + LocationLabel string `json:"location_label"` + Area LeadArea `json:"area"` + Saved bool `json:"saved"` + ResultCount int `json:"result_count"` + PagesFetched int `json:"pages_fetched"` + HasMore bool `json:"has_more"` + NextCursor string `json:"-"` + LastRunAt time.Time `json:"last_run_at"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` +} + +// LeadEnrichmentRun is one background pass reading leads' websites. +type LeadEnrichmentRun struct { + ID uuid.UUID `json:"id"` + OrganizationID uuid.UUID `json:"-"` + RequestedByUserID *uuid.UUID `json:"requested_by_user_id"` + LeadIDs []uuid.UUID `json:"-"` + Verify bool `json:"verify"` + People bool `json:"people"` + Status string `json:"status"` + Total int `json:"total"` + Processed int `json:"processed"` + EmailsFound int `json:"emails_found"` + PeopleFound int `json:"people_found"` + NoWebsite int `json:"no_website"` + Failed int `json:"failed"` + CreditsConsumed int `json:"credits_consumed"` + LastError string `json:"last_error"` + StartedAt *time.Time `json:"started_at"` + FinishedAt *time.Time `json:"finished_at"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` +} + +// LeadSort orders a lead list. +type LeadSort string + +const ( + LeadSortRecent LeadSort = "recent" + LeadSortScore LeadSort = "score" + LeadSortRating LeadSort = "rating" + LeadSortReviews LeadSort = "reviews" + LeadSortName LeadSort = "name" +) + +// Valid reports whether the sort is one the list understands. +func (s LeadSort) Valid() bool { + switch s { + case LeadSortRecent, LeadSortScore, LeadSortRating, LeadSortReviews, LeadSortName: + return true + } + return false +} + +// LeadFilter narrows a workspace's leads. Every field is optional. +type LeadFilter struct { + SearchID *uuid.UUID `json:"search_id,omitempty"` + Q string `json:"q,omitempty"` + Statuses []LeadStatus `json:"statuses,omitempty"` + Providers []LeadProvider `json:"providers,omitempty"` + Category string `json:"category,omitempty"` + Tag string `json:"tag,omitempty"` + HasEmail *bool `json:"has_email,omitempty"` + HasWebsite *bool `json:"has_website,omitempty"` + HasPhone *bool `json:"has_phone,omitempty"` + HasSocials *bool `json:"has_socials,omitempty"` + HasPeople *bool `json:"has_people,omitempty"` + InContacts *bool `json:"in_contacts,omitempty"` + Enrichment []LeadEnrichmentStatus `json:"enrichment,omitempty"` + MinRating *float64 `json:"min_rating,omitempty"` + MinReviews *int `json:"min_reviews,omitempty"` + MaxReviews *int `json:"max_reviews,omitempty"` + MinScore *int `json:"min_score,omitempty"` + Bounds *LeadBounds `json:"bounds,omitempty"` + ExcludeChain bool `json:"exclude_chains,omitempty"` +} + +// LeadSelection names a set of leads: explicit ids, or every lead matching a +// filter. +type LeadSelection struct { + LeadIDs []uuid.UUID `json:"lead_ids,omitempty"` + All bool `json:"all,omitempty"` + Filter *LeadFilter `json:"filter,omitempty"` +} + +// LeadPatch is the editable part of a lead. Nil fields are left alone. +type LeadPatch struct { + Status *LeadStatus `json:"status,omitempty"` + Notes *string `json:"notes,omitempty"` + Tags *[]string `json:"tags,omitempty"` + AddTags []string `json:"add_tags,omitempty"` + RemoveTags []string `json:"remove_tags,omitempty"` +} diff --git a/internal/models/org_transfer.go b/internal/models/org_transfer.go index e029f617a..18a922fb6 100644 --- a/internal/models/org_transfer.go +++ b/internal/models/org_transfer.go @@ -119,7 +119,7 @@ type OrgDataGroupInfo struct { // blanks those when their target is not part of the run. var OrgDataGroupCatalog = []OrgDataGroupInfo{ {Key: OrgDataGroupCore, Label: "Workspace", Description: "Organization, members, roles, teams, mailboxes, mailbox tags, API keys, webhooks, and settings.", Required: true}, - {Key: OrgDataGroupContacts, Label: "Contacts", Description: "Contacts, categories, notes, activities, and the suppression list."}, + {Key: OrgDataGroupContacts, Label: "Contacts", Description: "Contacts, categories, notes, activities, lead finder leads, and the suppression list."}, {Key: OrgDataGroupCampaigns, Label: "Campaigns", Description: "Campaigns, folders, sequences, senders, attachments, and per-campaign settings.", Requires: []OrgDataGroup{OrgDataGroupContacts}}, {Key: OrgDataGroupCRM, Label: "CRM", Description: "Pipelines, deals, tasks, and meeting bookings."}, {Key: OrgDataGroupAutomations, Label: "Automations", Description: "Automations, connected integrations, and lead sync sources."}, diff --git a/internal/models/segment.go b/internal/models/segment.go index af8d1957c..29878d69c 100644 --- a/internal/models/segment.go +++ b/internal/models/segment.go @@ -141,7 +141,7 @@ var SegmentFieldCatalog = []SegmentFieldSpec{ {Field: "phone", Label: "Phone", Group: "Contact", Kind: SegmentFieldText}, {Field: "subscribed", Label: "Subscribed", Group: "Contact", Kind: SegmentFieldBool}, {Field: "suppressed", Label: "On the suppression list", Group: "Contact", Kind: SegmentFieldBool}, - {Field: "source", Label: "Source", Group: "Contact", Kind: SegmentFieldEnum, Options: []string{"unknown", "manual", "campaign", "import", "sheet_sync", "api", "ai_assistant", "form", "apollo", "clay"}}, + {Field: "source", Label: "Source", Group: "Contact", Kind: SegmentFieldEnum, Options: []string{"unknown", "manual", "campaign", "import", "sheet_sync", "api", "ai_assistant", "form", "apollo", "clay", "lead_finder"}}, {Field: "verification_status", Label: "Verification status", Group: "Contact", Kind: SegmentFieldEnum, Options: []string{"valid", "risky", "invalid", "unknown"}}, {Field: "is_catch_all", Label: "Catch-all domain", Group: "Contact", Kind: SegmentFieldBool}, {Field: "mail_host", Label: "Email provider", Group: "Contact", Kind: SegmentFieldEnum, Options: mailHostOptions(), OptionLabels: mailHostLabels()}, diff --git a/internal/repository/lead_finder_live_test.go b/internal/repository/lead_finder_live_test.go new file mode 100644 index 000000000..8e3da89ef --- /dev/null +++ b/internal/repository/lead_finder_live_test.go @@ -0,0 +1,211 @@ +package repository + +import ( + "context" + "errors" + "testing" + + "github.com/google/uuid" + + "github.com/warmbly/warmbly/internal/models" +) + +// The lead finder's writes merge what a source says into what is known, and +// every read and write stays inside the organization. +// +// WARMBLY_TEST_DB=postgres://warmbly:warmbly@localhost:15432/warmbly_dev?sslmode=disable \ +// go test ./internal/repository/ -run LiveLeadFinder -v +func TestLiveLeadFinder(t *testing.T) { + _, pool := liveContactDB(t) + requireSchemaVersion(t, pool, 363) + ctx := context.Background() + repo := NewLeadFinderRepository(pool) + + user := uuid.New() + orgA, orgB := uuid.New(), uuid.New() + exec := func(sql string, args ...any) { + t.Helper() + if _, err := pool.Exec(ctx, sql, args...); err != nil { + t.Fatalf("fixture %q: %v", sql[:min(60, len(sql))], err) + } + } + exec(`INSERT INTO users (id, email, first_name, last_name, password_hash) VALUES ($1, $2, 'Lead', 'Finder', 'x')`, + user, "lf-"+user.String()[:8]+"@test.local") + for _, org := range []uuid.UUID{orgA, orgB} { + exec(`INSERT INTO organizations (id, name, slug, owner_user_id) VALUES ($1, 'Lead Finder', $2, $3)`, org, "lf-"+org.String()[:8], user) + } + t.Cleanup(func() { + _, _ = pool.Exec(ctx, `DELETE FROM organizations WHERE id = ANY($1)`, []uuid.UUID{orgA, orgB}) + _, _ = pool.Exec(ctx, `DELETE FROM users WHERE id = $1`, user) + }) + + rating := 4.6 + reviews := 120 + search := &models.LeadSearch{OrganizationID: orgA, CreatedByUserID: &user, Name: "Dentists", Provider: models.LeadProviderOSM, + Area: models.LeadArea{Kind: models.LeadAreaBBox, Bounds: models.LeadBounds{South: 47, West: 19, North: 48, East: 20}}} + if err := repo.CreateSearch(ctx, search); err != nil { + t.Fatal(err) + } + first := []models.Lead{ + {Provider: models.LeadProviderOSM, ExternalID: "node/1", Name: "Bright Smiles", Category: "Dentist", Latitude: 47.5, Longitude: 19.05, + Phone: "+36 1 555 0100", Website: "https://brightsmiles.hu", Domain: "brightsmiles.hu", Rating: &rating, ReviewCount: &reviews, + Socials: map[string]string{"facebook": "https://facebook.com/bright"}}, + {Provider: models.LeadProviderOSM, ExternalID: "node/2", Name: "Corner Dental", Category: "Dentist", Latitude: 47.6, Longitude: 19.1}, + } + ids, err := repo.UpsertLeads(ctx, orgA, &search.ID, first) + if err != nil { + t.Fatal(err) + } + if len(ids) != 2 { + t.Fatalf("ids = %v", ids) + } + + // A later answer without the phone keeps the phone, and adds what is new. + again := []models.Lead{{Provider: models.LeadProviderOSM, ExternalID: "node/1", Name: "Bright Smiles Dental", Latitude: 47.5, Longitude: 19.05, + Socials: map[string]string{"instagram": "https://instagram.com/bright"}}} + if _, err := repo.UpsertLeads(ctx, orgA, nil, again); err != nil { + t.Fatal(err) + } + l, err := repo.GetLead(ctx, orgA, ids[0]) + if err != nil || l == nil { + t.Fatalf("get: %v %v", l, err) + } + if l.Name != "Bright Smiles Dental" || l.Phone != "+36 1 555 0100" || l.Website == "" || l.Rating == nil || len(l.Socials) != 2 { + t.Fatalf("merge lost or ignored a field: %+v", l) + } + if l.Score != 15+15+10+10+10 { + t.Fatalf("score = %d", l.Score) + } + if got, err := repo.GetLead(ctx, orgB, ids[0]); err != nil || got != nil { + t.Fatalf("another organization read the lead: %v %v", got, err) + } + + // Enrichment stores the primary address and rescores. + l.Email = "info@brightsmiles.hu" + l.Emails = []models.LeadEmail{{Email: "info@brightsmiles.hu", Source: "website", DomainMatch: true, Status: "valid"}} + l.EnrichmentStatus = models.LeadEnrichmentDone + if err := repo.SaveEnrichment(ctx, l); err != nil { + t.Fatal(err) + } + if l, _ = repo.GetLead(ctx, orgA, ids[0]); l.Score != 100 || l.EnrichedAt == nil { + t.Fatalf("after enrichment: score %d enriched %v", l.Score, l.EnrichedAt) + } + + yes := true + minRating := 4.0 + got, total, err := repo.ListLeads(ctx, orgA, &models.LeadFilter{SearchID: &search.ID, HasEmail: &yes, MinRating: &minRating}, models.LeadSortScore, 10, 0) + if err != nil || total != 1 || len(got) != 1 || got[0].ID != ids[0] { + t.Fatalf("filtered list = %d %v %v", total, got, err) + } + if _, total, _ = repo.ListLeads(ctx, orgA, &models.LeadFilter{Q: "corner"}, models.LeadSortName, 10, 0); total != 1 { + t.Fatalf("text filter total = %d", total) + } + if _, total, err = repo.ListLeads(ctx, orgB, nil, models.LeadSortRecent, 10, 0); err != nil || total != 0 { + t.Fatalf("another organization lists %d leads: %v", total, err) + } + + // Tags converge, and a patch from another organization changes nothing. + saved := models.LeadStatusSaved + if n, err := repo.PatchLeads(ctx, orgA, ids, &models.LeadPatch{Status: &saved, AddTags: []string{"hot", "hot", "q4"}}); err != nil || n != 2 { + t.Fatalf("patch = %d %v", n, err) + } + if _, err := repo.PatchLeads(ctx, orgA, ids, &models.LeadPatch{AddTags: []string{"q4"}, RemoveTags: []string{"hot"}}); err != nil { + t.Fatal(err) + } + if n, err := repo.PatchLeads(ctx, orgB, ids, &models.LeadPatch{Status: &saved}); err != nil || n != 0 { + t.Fatalf("another organization patched the leads: %d %v", n, err) + } + if l, _ = repo.GetLead(ctx, orgA, ids[1]); len(l.Tags) != 1 || l.Tags[0] != "q4" || l.Status != models.LeadStatusSaved { + t.Fatalf("tags %v status %s", l.Tags, l.Status) + } + + // A selection never reaches past the organization. + sel, err := repo.ResolveSelection(ctx, orgB, &models.LeadSelection{LeadIDs: ids}, 100) + if err != nil || len(sel) != 0 { + t.Fatalf("other org resolved %v %v", sel, err) + } + if sel, _ = repo.ResolveSelection(ctx, orgA, &models.LeadSelection{All: true, Filter: &models.LeadFilter{Tag: "q4"}}, 100); len(sel) != 2 { + t.Fatalf("all matching = %v", sel) + } + + // A contact from another organization is never linked. + contactB := uuid.New() + exec(`INSERT INTO contacts (id, user_id, organization_id, email, first_name, last_name, company, phone, custom_fields, updated_at, created_at) + VALUES ($1, $2, $3, 'x@other.test', '', '', '', '', '{}', NOW(), NOW())`, contactB, user, orgB) + if err := repo.LinkContacts(ctx, orgA, map[uuid.UUID]uuid.UUID{ids[0]: contactB}); err != nil { + t.Fatal(err) + } + if l, _ = repo.GetLead(ctx, orgA, ids[0]); l.ContactID != nil { + t.Fatal("linked a contact from another organization") + } + + // People are matched by name and stay inside the organization; a website + // read never replaces a typed-in address, and a published one beats a guess. + at, dom := "@", "brightsmiles.hu" + people := []models.LeadPerson{ + {Name: "Jane Doe", NameKey: "jane doe", FirstName: "Jane", LastName: "Doe", Title: "Owner", Seniority: models.LeadSeniorityOwner, + Email: "jane" + at + dom, EmailSource: models.LeadEmailManual, Source: models.LeadPersonManual}, + {Name: "Ravi Patel", NameKey: "ravi patel", FirstName: "Ravi", LastName: "Patel", Seniority: models.LeadSeniorityStaff, + Email: "ravi" + at + dom, EmailSource: models.LeadEmailPattern, EmailStatus: models.LeadPersonStatusGuessed, EmailConfidence: 25, + Source: models.LeadPersonPage}, + } + stored, err := repo.SavePeople(ctx, orgA, ids[0], people) + if err != nil || len(stored) != 2 { + t.Fatalf("save people = %v %v", stored, err) + } + if _, err := repo.SavePeople(ctx, orgB, ids[0], people); !errors.Is(err, ErrLeadNotFound) { + t.Fatalf("another organization saved people onto the lead: %v", err) + } + reread := []models.LeadPerson{ + {Name: "Jane Doe", NameKey: "jane doe", FirstName: "Jane", LastName: "Doe", Title: "Founder", Seniority: models.LeadSeniorityOwner, + Email: "j.doe" + at + dom, EmailSource: models.LeadEmailWebsite, EmailConfidence: 80, Source: models.LeadPersonPage}, + {Name: "Ravi Patel", NameKey: "ravi patel", FirstName: "Ravi", LastName: "Patel", Title: "Associate", Seniority: models.LeadSeniorityStaff, + Email: "ravi.patel" + at + dom, EmailSource: models.LeadEmailWebsite, EmailConfidence: 80, Source: models.LeadPersonPage}, + } + if _, err := repo.SavePeople(ctx, orgA, ids[0], reread); err != nil { + t.Fatal(err) + } + byLead, err := repo.PeopleForLeads(ctx, orgA, ids) + if err != nil || len(byLead[ids[0]]) != 2 { + t.Fatalf("people = %v %v", byLead, err) + } + jane, ravi := byLead[ids[0]][0], byLead[ids[0]][1] + if jane.Name != "Jane Doe" || jane.Email != "jane"+at+dom || jane.Title != "Owner" { + t.Fatalf("a typed-in person was overwritten: %+v", jane) + } + if ravi.Email != "ravi.patel"+at+dom || ravi.EmailSource != models.LeadEmailWebsite || ravi.Title != "Associate" { + t.Fatalf("a guess did not give way to a published address: %+v", ravi) + } + if other, err := repo.PeopleForLeads(ctx, orgB, ids); err != nil || len(other) != 0 { + t.Fatalf("another organization read the people: %v %v", other, err) + } + if l, _ = repo.GetLead(ctx, orgA, ids[0]); l.PeopleCount != 2 { + t.Fatalf("people_count = %d", l.PeopleCount) + } + if _, total, _ = repo.ListLeads(ctx, orgA, &models.LeadFilter{HasPeople: &yes}, models.LeadSortRecent, 10, 0); total != 1 { + t.Fatalf("has_people total = %d", total) + } + ravi.Name, ravi.NameKey, ravi.FirstName, ravi.LastName = "Jane Doe", "jane doe", "Jane", "Doe" + if _, err := repo.SavePeople(ctx, orgA, ids[0], []models.LeadPerson{ravi}); !errors.Is(err, ErrLeadPersonExists) { + t.Fatalf("renaming onto someone already there = %v", err) + } + if err := repo.LinkPersonContacts(ctx, orgA, map[uuid.UUID]uuid.UUID{jane.ID: contactB}); err != nil { + t.Fatal(err) + } + if p, _ := repo.GetPerson(ctx, orgA, ids[0], jane.ID); p == nil || p.ContactID != nil { + t.Fatal("linked a person to a contact from another organization") + } + if ok, err := repo.DeletePerson(ctx, orgB, ids[0], jane.ID); err != nil || ok { + t.Fatalf("another organization removed a person: %v %v", ok, err) + } + if ok, err := repo.DeletePerson(ctx, orgA, ids[0], jane.ID); !ok || err != nil { + t.Fatalf("delete person = %v %v", ok, err) + } + + if err := repo.RecordSearchPage(ctx, search); err != nil || search.ResultCount != 2 { + t.Fatalf("search count = %d %v", search.ResultCount, err) + } + if n, err := repo.DeleteLeads(ctx, orgB, ids); err != nil || n != 0 { + t.Fatalf("another organization deleted the leads: %d %v", n, err) + } +} diff --git a/internal/repository/pg_lead_finder.go b/internal/repository/pg_lead_finder.go new file mode 100644 index 000000000..aa4f3a2bc --- /dev/null +++ b/internal/repository/pg_lead_finder.go @@ -0,0 +1,845 @@ +package repository + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "strings" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + + "github.com/warmbly/warmbly/internal/models" +) + +// ErrLeadSearchNotFound means the search is not in the organization. +var ErrLeadSearchNotFound = errors.New("lead search not found") + +// ErrLeadNotFound is returned when a lead is not the organization's. +var ErrLeadNotFound = errors.New("lead not found") + +// LeadPoint is the slice of a lead the map draws. +type LeadPoint struct { + ID uuid.UUID `json:"id"` + Name string `json:"name"` + Category string `json:"category"` + Latitude float64 `json:"latitude"` + Longitude float64 `json:"longitude"` + Status models.LeadStatus `json:"status"` + Score int `json:"score"` + HasEmail bool `json:"has_email"` + HasSite bool `json:"has_website"` + HasPhone bool `json:"has_phone"` + Rating *float64 `json:"rating"` + Reviews *int `json:"review_count"` + InContact bool `json:"in_contacts"` +} + +// LeadFacet is one value of a filterable field and how many leads carry it. +type LeadFacet struct { + Value string `json:"value"` + Count int `json:"count"` +} + +// LeadFacets are the values the filter panel offers for the current scope. +type LeadFacets struct { + Categories []LeadFacet `json:"categories"` + Tags []LeadFacet `json:"tags"` + Cities []LeadFacet `json:"cities"` +} + +// LeadFinderRepository persists leads, the searches that found them and the +// runs that read their websites. Every org-scoped call takes the organization. +type LeadFinderRepository interface { + UpsertLeads(ctx context.Context, orgID uuid.UUID, searchID *uuid.UUID, leads []models.Lead) ([]uuid.UUID, error) + GetLead(ctx context.Context, orgID, id uuid.UUID) (*models.Lead, error) + LeadsByIDs(ctx context.Context, orgID uuid.UUID, ids []uuid.UUID) ([]models.Lead, error) + ListLeads(ctx context.Context, orgID uuid.UUID, f *models.LeadFilter, sort models.LeadSort, limit, offset int) ([]models.Lead, int64, error) + LeadPoints(ctx context.Context, orgID uuid.UUID, f *models.LeadFilter, limit int) ([]LeadPoint, error) + LeadFacets(ctx context.Context, orgID uuid.UUID, f *models.LeadFilter) (*LeadFacets, error) + ResolveSelection(ctx context.Context, orgID uuid.UUID, sel *models.LeadSelection, limit int) ([]uuid.UUID, error) + PatchLeads(ctx context.Context, orgID uuid.UUID, ids []uuid.UUID, p *models.LeadPatch) (int64, error) + DeleteLeads(ctx context.Context, orgID uuid.UUID, ids []uuid.UUID) (int64, error) + MarkQueued(ctx context.Context, orgID uuid.UUID, ids []uuid.UUID) error + SaveEnrichment(ctx context.Context, l *models.Lead) error + LinkContacts(ctx context.Context, orgID uuid.UUID, links map[uuid.UUID]uuid.UUID) error + SuppressedEmails(ctx context.Context, orgID uuid.UUID, emails []string) (map[string]bool, error) + SaveSite(ctx context.Context, orgID, leadID uuid.UUID, site models.LeadSite) error + + PeopleForLeads(ctx context.Context, orgID uuid.UUID, leadIDs []uuid.UUID) (map[uuid.UUID][]models.LeadPerson, error) + GetPerson(ctx context.Context, orgID, leadID, id uuid.UUID) (*models.LeadPerson, error) + SavePeople(ctx context.Context, orgID, leadID uuid.UUID, people []models.LeadPerson) ([]models.LeadPerson, error) + DeletePerson(ctx context.Context, orgID, leadID, id uuid.UUID) (bool, error) + LinkPersonContacts(ctx context.Context, orgID uuid.UUID, links map[uuid.UUID]uuid.UUID) error + + CreateSearch(ctx context.Context, s *models.LeadSearch) error + GetSearch(ctx context.Context, orgID, id uuid.UUID) (*models.LeadSearch, error) + ListSearches(ctx context.Context, orgID uuid.UUID, savedOnly bool, limit int) ([]models.LeadSearch, error) + RecordSearchPage(ctx context.Context, s *models.LeadSearch) error + UpdateSearch(ctx context.Context, orgID, id uuid.UUID, name *string, saved *bool) (*models.LeadSearch, error) + DeleteSearch(ctx context.Context, orgID, id uuid.UUID) (bool, error) + + CreateEnrichmentRun(ctx context.Context, run *models.LeadEnrichmentRun) error + GetEnrichmentRun(ctx context.Context, orgID, id uuid.UUID) (*models.LeadEnrichmentRun, error) + ActiveEnrichmentRuns(ctx context.Context, orgID uuid.UUID) ([]models.LeadEnrichmentRun, error) + ClaimEnrichmentRun(ctx context.Context, id uuid.UUID) (*models.LeadEnrichmentRun, error) + DueEnrichmentRuns(ctx context.Context, limit int) ([]uuid.UUID, error) + UpdateEnrichmentProgress(ctx context.Context, run *models.LeadEnrichmentRun) error + FinishEnrichmentRun(ctx context.Context, run *models.LeadEnrichmentRun) error +} + +type leadFinderRepository struct { + db *pgxpool.Pool +} + +// NewLeadFinderRepository builds the Postgres lead finder repository. +func NewLeadFinderRepository(db *pgxpool.Pool) LeadFinderRepository { + return &leadFinderRepository{db: db} +} + +// --- leads ------------------------------------------------------------------ + +const leadColumns = `l.id, l.organization_id, l.provider, l.external_id, l.name, l.category, l.categories, l.address, + l.street, l.city, l.region, l.postcode, l.country, l.latitude, l.longitude, l.phone, l.website, l.domain, + l.email, l.emails, l.socials, l.rating, l.review_count, l.price_level, l.hours, l.business_status, l.maps_url, + l.description, l.chain, l.site, l.score, l.status, l.enrichment_status, l.enriched_at, l.contact_id, l.tags, + l.notes, l.first_seen_at, l.last_seen_at, l.created_at, l.updated_at, + (SELECT COUNT(*) FROM lead_people lp WHERE lp.lead_id = l.id)` + +// leadScoreSQL rates how reachable a lead is, 0 to 100, from the row itself. +const leadScoreSQL = `LEAST(100, + (CASE WHEN website <> '' THEN 15 ELSE 0 END) + + (CASE WHEN email <> '' THEN 25 ELSE 0 END) + + (CASE WHEN EXISTS (SELECT 1 FROM jsonb_array_elements(emails) e WHERE e->>'email' = email AND e->>'status' = 'valid') THEN 15 ELSE 0 END) + + (CASE WHEN phone <> '' THEN 15 ELSE 0 END) + + (CASE WHEN socials <> '{}'::jsonb THEN 10 ELSE 0 END) + + (CASE WHEN rating >= 4 THEN 10 WHEN rating >= 3 THEN 5 ELSE 0 END) + + (CASE WHEN review_count >= 25 THEN 10 WHEN review_count >= 5 THEN 5 ELSE 0 END))` + +func scanLead(row pgx.Row) (models.Lead, error) { + var l models.Lead + var emails, socials, hours, site []byte + var rating *float64 + var reviews, price *int32 + err := row.Scan(&l.ID, &l.OrganizationID, &l.Provider, &l.ExternalID, &l.Name, &l.Category, &l.Categories, + &l.Address, &l.Street, &l.City, &l.Region, &l.Postcode, &l.Country, &l.Latitude, &l.Longitude, &l.Phone, + &l.Website, &l.Domain, &l.Email, &emails, &socials, &rating, &reviews, &price, &hours, &l.BusinessStatus, + &l.MapsURL, &l.Description, &l.Chain, &site, &l.Score, &l.Status, &l.EnrichmentStatus, &l.EnrichedAt, + &l.ContactID, &l.Tags, &l.Notes, &l.FirstSeenAt, &l.LastSeenAt, &l.CreatedAt, &l.UpdatedAt, &l.PeopleCount) + if err != nil { + return l, err + } + l.Rating = rating + if reviews != nil { + v := int(*reviews) + l.ReviewCount = &v + } + if price != nil { + v := int(*price) + l.PriceLevel = &v + } + l.Emails = []models.LeadEmail{} + l.Socials = map[string]string{} + l.Hours = []string{} + _ = json.Unmarshal(emails, &l.Emails) + _ = json.Unmarshal(socials, &l.Socials) + _ = json.Unmarshal(hours, &l.Hours) + _ = json.Unmarshal(site, &l.Site) + if l.Categories == nil { + l.Categories = []string{} + } + if l.Tags == nil { + l.Tags = []string{} + } + return l, nil +} + +func jsonOr(v any, empty string) []byte { + b, err := json.Marshal(v) + if err != nil || string(b) == "null" { + return []byte(empty) + } + return b +} + +// UpsertLeads writes what a provider returned. A field the provider left empty +// never blanks one already known, and nothing a person set is touched. +func (r *leadFinderRepository) UpsertLeads(ctx context.Context, orgID uuid.UUID, searchID *uuid.UUID, leads []models.Lead) ([]uuid.UUID, error) { + if len(leads) == 0 { + return []uuid.UUID{}, nil + } + tx, err := r.db.Begin(ctx) + if err != nil { + return nil, err + } + defer func() { _ = tx.Rollback(ctx) }() + + batch := &pgx.Batch{} + for i := range leads { + l := &leads[i] + cats := l.Categories + if cats == nil { + cats = []string{} + } + batch.Queue(` + INSERT INTO leads (organization_id, provider, external_id, name, category, categories, address, street, + city, region, postcode, country, latitude, longitude, phone, website, domain, email, emails, socials, + rating, review_count, price_level, hours, business_status, maps_url, description, chain) + VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20,$21,$22,$23,$24,$25,$26,$27,$28) + ON CONFLICT (organization_id, provider, external_id) DO UPDATE SET + name = COALESCE(NULLIF(EXCLUDED.name, ''), leads.name), + category = COALESCE(NULLIF(EXCLUDED.category, ''), leads.category), + categories = CASE WHEN cardinality(EXCLUDED.categories) > 0 THEN EXCLUDED.categories ELSE leads.categories END, + address = COALESCE(NULLIF(EXCLUDED.address, ''), leads.address), + street = COALESCE(NULLIF(EXCLUDED.street, ''), leads.street), + city = COALESCE(NULLIF(EXCLUDED.city, ''), leads.city), + region = COALESCE(NULLIF(EXCLUDED.region, ''), leads.region), + postcode = COALESCE(NULLIF(EXCLUDED.postcode, ''), leads.postcode), + country = COALESCE(NULLIF(EXCLUDED.country, ''), leads.country), + latitude = EXCLUDED.latitude, + longitude = EXCLUDED.longitude, + phone = COALESCE(NULLIF(EXCLUDED.phone, ''), leads.phone), + website = COALESCE(NULLIF(EXCLUDED.website, ''), leads.website), + domain = COALESCE(NULLIF(EXCLUDED.domain, ''), leads.domain), + email = COALESCE(NULLIF(leads.email, ''), EXCLUDED.email), + emails = CASE WHEN leads.emails = '[]'::jsonb THEN EXCLUDED.emails ELSE leads.emails END, + socials = leads.socials || EXCLUDED.socials, + rating = COALESCE(EXCLUDED.rating, leads.rating), + review_count = COALESCE(EXCLUDED.review_count, leads.review_count), + price_level = COALESCE(EXCLUDED.price_level, leads.price_level), + hours = CASE WHEN EXCLUDED.hours <> '[]'::jsonb THEN EXCLUDED.hours ELSE leads.hours END, + business_status = COALESCE(NULLIF(EXCLUDED.business_status, ''), leads.business_status), + maps_url = COALESCE(NULLIF(EXCLUDED.maps_url, ''), leads.maps_url), + description = COALESCE(NULLIF(EXCLUDED.description, ''), leads.description), + chain = COALESCE(NULLIF(EXCLUDED.chain, ''), leads.chain), + last_seen_at = NOW(), + updated_at = NOW() + RETURNING id`, + orgID, l.Provider, l.ExternalID, l.Name, l.Category, cats, l.Address, l.Street, l.City, l.Region, + l.Postcode, l.Country, l.Latitude, l.Longitude, l.Phone, l.Website, l.Domain, l.Email, + jsonOr(l.Emails, "[]"), jsonOr(l.Socials, "{}"), l.Rating, l.ReviewCount, l.PriceLevel, + jsonOr(l.Hours, "[]"), l.BusinessStatus, l.MapsURL, l.Description, l.Chain) + } + res := tx.SendBatch(ctx, batch) + ids := make([]uuid.UUID, 0, len(leads)) + for range leads { + var id uuid.UUID + if err := res.QueryRow().Scan(&id); err != nil { + _ = res.Close() + return nil, err + } + ids = append(ids, id) + } + if err := res.Close(); err != nil { + return nil, err + } + if _, err := tx.Exec(ctx, `UPDATE leads SET score = `+leadScoreSQL+` WHERE id = ANY($1)`, ids); err != nil { + return nil, err + } + if searchID != nil { + if _, err := tx.Exec(ctx, ` + INSERT INTO lead_search_hits (search_id, lead_id) + SELECT $1, UNNEST($2::uuid[]) + ON CONFLICT (search_id, lead_id) DO UPDATE SET seen_at = NOW()`, *searchID, ids); err != nil { + return nil, err + } + } + return ids, tx.Commit(ctx) +} + +func (r *leadFinderRepository) GetLead(ctx context.Context, orgID, id uuid.UUID) (*models.Lead, error) { + l, err := scanLead(r.db.QueryRow(ctx, `SELECT `+leadColumns+` FROM leads l WHERE l.organization_id = $1 AND l.id = $2`, orgID, id)) + if isNoRows(err) { + return nil, nil + } + if err != nil { + return nil, err + } + return &l, nil +} + +func (r *leadFinderRepository) LeadsByIDs(ctx context.Context, orgID uuid.UUID, ids []uuid.UUID) ([]models.Lead, error) { + out := []models.Lead{} + if len(ids) == 0 { + return out, nil + } + rows, err := r.db.Query(ctx, `SELECT `+leadColumns+` FROM leads l WHERE l.organization_id = $1 AND l.id = ANY($2) + ORDER BY array_position($2::uuid[], l.id)`, orgID, ids) + if err != nil { + return nil, err + } + defer rows.Close() + for rows.Next() { + l, err := scanLead(rows) + if err != nil { + return nil, err + } + out = append(out, l) + } + return out, rows.Err() +} + +// leadWhere renders a filter as a WHERE clause over leads l. $1 is always the +// organization; further arguments are appended to args. +func leadWhere(orgID uuid.UUID, f *models.LeadFilter) (string, []any) { + args := []any{orgID} + conds := []string{"l.organization_id = $1"} + arg := func(v any) string { + args = append(args, v) + return fmt.Sprintf("$%d", len(args)) + } + boolCond := func(v *bool, yes string) { + if v == nil { + return + } + if *v { + conds = append(conds, yes) + } else { + conds = append(conds, "NOT ("+yes+")") + } + } + if f == nil { + return strings.Join(conds, " AND "), args + } + if f.SearchID != nil { + conds = append(conds, "EXISTS (SELECT 1 FROM lead_search_hits h WHERE h.lead_id = l.id AND h.search_id = "+arg(*f.SearchID)+")") + } + if q := strings.TrimSpace(f.Q); q != "" { + p := arg("%" + escapeLike(q) + "%") + conds = append(conds, "(l.name ILIKE "+p+" OR l.address ILIKE "+p+" OR l.domain ILIKE "+p+" OR l.email ILIKE "+p+" OR l.category ILIKE "+p+")") + } + if len(f.Statuses) > 0 { + s := make([]string, 0, len(f.Statuses)) + for _, v := range f.Statuses { + s = append(s, string(v)) + } + conds = append(conds, "l.status = ANY("+arg(s)+")") + } + if len(f.Providers) > 0 { + s := make([]string, 0, len(f.Providers)) + for _, v := range f.Providers { + s = append(s, string(v)) + } + conds = append(conds, "l.provider = ANY("+arg(s)+")") + } + if len(f.Enrichment) > 0 { + s := make([]string, 0, len(f.Enrichment)) + for _, v := range f.Enrichment { + s = append(s, string(v)) + } + conds = append(conds, "l.enrichment_status = ANY("+arg(s)+")") + } + if c := strings.TrimSpace(f.Category); c != "" { + p := arg(c) + conds = append(conds, "(l.category = "+p+" OR "+p+" = ANY(l.categories))") + } + if t := strings.TrimSpace(f.Tag); t != "" { + conds = append(conds, arg(t)+" = ANY(l.tags)") + } + boolCond(f.HasEmail, "l.email <> ''") + boolCond(f.HasWebsite, "l.website <> ''") + boolCond(f.HasPhone, "l.phone <> ''") + boolCond(f.HasSocials, "l.socials <> '{}'::jsonb") + boolCond(f.InContacts, "l.contact_id IS NOT NULL") + boolCond(f.HasPeople, "EXISTS (SELECT 1 FROM lead_people lp WHERE lp.lead_id = l.id)") + if f.MinRating != nil { + conds = append(conds, "l.rating >= "+arg(*f.MinRating)) + } + if f.MinReviews != nil { + conds = append(conds, "COALESCE(l.review_count, 0) >= "+arg(*f.MinReviews)) + } + if f.MaxReviews != nil { + conds = append(conds, "COALESCE(l.review_count, 0) <= "+arg(*f.MaxReviews)) + } + if f.MinScore != nil { + conds = append(conds, "l.score >= "+arg(*f.MinScore)) + } + if f.ExcludeChain { + conds = append(conds, "l.chain = ''") + } + if b := f.Bounds; b != nil { + conds = append(conds, "l.latitude BETWEEN "+arg(b.South)+" AND "+arg(b.North)) + if b.West <= b.East { + conds = append(conds, "l.longitude BETWEEN "+arg(b.West)+" AND "+arg(b.East)) + } else { + conds = append(conds, "(l.longitude >= "+arg(b.West)+" OR l.longitude <= "+arg(b.East)+")") + } + } + return strings.Join(conds, " AND "), args +} + +func leadOrder(sort models.LeadSort) string { + switch sort { + case models.LeadSortScore: + return "l.score DESC, l.last_seen_at DESC, l.id DESC" + case models.LeadSortRating: + return "l.rating DESC NULLS LAST, l.review_count DESC NULLS LAST, l.id DESC" + case models.LeadSortReviews: + return "l.review_count DESC NULLS LAST, l.id DESC" + case models.LeadSortName: + return "lower(l.name), l.id" + } + return "l.last_seen_at DESC, l.id DESC" +} + +func (r *leadFinderRepository) ListLeads(ctx context.Context, orgID uuid.UUID, f *models.LeadFilter, sort models.LeadSort, limit, offset int) ([]models.Lead, int64, error) { + where, args := leadWhere(orgID, f) + var total int64 + if err := r.db.QueryRow(ctx, `SELECT COUNT(*) FROM leads l WHERE `+where, args...).Scan(&total); err != nil { + return nil, 0, err + } + args = append(args, limit, offset) + rows, err := r.db.Query(ctx, fmt.Sprintf(`SELECT %s FROM leads l WHERE %s ORDER BY %s LIMIT $%d OFFSET $%d`, + leadColumns, where, leadOrder(sort), len(args)-1, len(args)), args...) + if err != nil { + return nil, 0, err + } + defer rows.Close() + out := []models.Lead{} + for rows.Next() { + l, err := scanLead(rows) + if err != nil { + return nil, 0, err + } + out = append(out, l) + } + return out, total, rows.Err() +} + +func (r *leadFinderRepository) LeadPoints(ctx context.Context, orgID uuid.UUID, f *models.LeadFilter, limit int) ([]LeadPoint, error) { + where, args := leadWhere(orgID, f) + args = append(args, limit) + rows, err := r.db.Query(ctx, fmt.Sprintf(` + SELECT l.id, l.name, l.category, l.latitude, l.longitude, l.status, l.score, l.email <> '', l.website <> '', + l.phone <> '', l.rating, l.review_count, l.contact_id IS NOT NULL + FROM leads l WHERE %s ORDER BY l.score DESC, l.id LIMIT $%d`, where, len(args)), args...) + if err != nil { + return nil, err + } + defer rows.Close() + out := []LeadPoint{} + for rows.Next() { + var p LeadPoint + var reviews *int32 + if err := rows.Scan(&p.ID, &p.Name, &p.Category, &p.Latitude, &p.Longitude, &p.Status, &p.Score, &p.HasEmail, + &p.HasSite, &p.HasPhone, &p.Rating, &reviews, &p.InContact); err != nil { + return nil, err + } + if reviews != nil { + v := int(*reviews) + p.Reviews = &v + } + out = append(out, p) + } + return out, rows.Err() +} + +func (r *leadFinderRepository) LeadFacets(ctx context.Context, orgID uuid.UUID, f *models.LeadFilter) (*LeadFacets, error) { + where, args := leadWhere(orgID, f) + facet := func(expr string) ([]LeadFacet, error) { + rows, err := r.db.Query(ctx, `SELECT v, COUNT(*) FROM (SELECT `+expr+` AS v FROM leads l WHERE `+where+`) s + WHERE v <> '' GROUP BY v ORDER BY COUNT(*) DESC, v LIMIT 50`, args...) + if err != nil { + return nil, err + } + defer rows.Close() + out := []LeadFacet{} + for rows.Next() { + var fc LeadFacet + if err := rows.Scan(&fc.Value, &fc.Count); err != nil { + return nil, err + } + out = append(out, fc) + } + return out, rows.Err() + } + var out LeadFacets + var err error + // Counts the primary and secondary categories once per lead, matching the category filter. + if out.Categories, err = facet("UNNEST(ARRAY(SELECT DISTINCT c FROM UNNEST(array_prepend(l.category, l.categories)) c))"); err != nil { + return nil, err + } + if out.Tags, err = facet("UNNEST(l.tags)"); err != nil { + return nil, err + } + if out.Cities, err = facet("l.city"); err != nil { + return nil, err + } + return &out, nil +} + +// ResolveSelection turns a selection into the organization's lead ids, at most limit. +func (r *leadFinderRepository) ResolveSelection(ctx context.Context, orgID uuid.UUID, sel *models.LeadSelection, limit int) ([]uuid.UUID, error) { + var rows pgx.Rows + var err error + if sel.All { + where, args := leadWhere(orgID, sel.Filter) + args = append(args, limit) + rows, err = r.db.Query(ctx, fmt.Sprintf(`SELECT l.id FROM leads l WHERE %s ORDER BY l.score DESC, l.id LIMIT $%d`, where, len(args)), args...) + } else { + if len(sel.LeadIDs) == 0 { + return []uuid.UUID{}, nil + } + rows, err = r.db.Query(ctx, `SELECT id FROM leads WHERE organization_id = $1 AND id = ANY($2) + ORDER BY array_position($2::uuid[], id) LIMIT $3`, orgID, sel.LeadIDs, limit) + } + if err != nil { + return nil, err + } + defer rows.Close() + out := []uuid.UUID{} + for rows.Next() { + var id uuid.UUID + if err := rows.Scan(&id); err != nil { + return nil, err + } + out = append(out, id) + } + return out, rows.Err() +} + +func (r *leadFinderRepository) PatchLeads(ctx context.Context, orgID uuid.UUID, ids []uuid.UUID, p *models.LeadPatch) (int64, error) { + if len(ids) == 0 { + return 0, nil + } + var status, notes *string + if p.Status != nil { + s := string(*p.Status) + status = &s + } + notes = p.Notes + var tags []string + if p.Tags != nil { + tags = *p.Tags + if tags == nil { + tags = []string{} + } + } + add := p.AddTags + if add == nil { + add = []string{} + } + remove := p.RemoveTags + if remove == nil { + remove = []string{} + } + tag, err := r.db.Exec(ctx, ` + UPDATE leads SET + status = COALESCE($3, status), + notes = COALESCE($4, notes), + tags = ARRAY( + SELECT DISTINCT t FROM UNNEST(COALESCE($5::text[], tags) || $6::text[]) AS t + WHERE t <> '' AND NOT (t = ANY($7::text[])) ORDER BY t), + updated_at = NOW() + WHERE organization_id = $1 AND id = ANY($2)`, orgID, ids, status, notes, tags, add, remove) + if err != nil { + return 0, err + } + return tag.RowsAffected(), nil +} + +func (r *leadFinderRepository) DeleteLeads(ctx context.Context, orgID uuid.UUID, ids []uuid.UUID) (int64, error) { + if len(ids) == 0 { + return 0, nil + } + tag, err := r.db.Exec(ctx, `DELETE FROM leads WHERE organization_id = $1 AND id = ANY($2)`, orgID, ids) + if err != nil { + return 0, err + } + return tag.RowsAffected(), nil +} + +func (r *leadFinderRepository) MarkQueued(ctx context.Context, orgID uuid.UUID, ids []uuid.UUID) error { + _, err := r.db.Exec(ctx, `UPDATE leads SET enrichment_status = 'queued', updated_at = NOW() + WHERE organization_id = $1 AND id = ANY($2)`, orgID, ids) + return err +} + +// SaveEnrichment stores what reading a lead's website found and rescores it. +func (r *leadFinderRepository) SaveEnrichment(ctx context.Context, l *models.Lead) error { + _, err := r.db.Exec(ctx, ` + UPDATE leads SET + email = $3, emails = $4, socials = $5, site = $6, phone = COALESCE(NULLIF($7, ''), phone), enrichment_status = $8, + website = COALESCE(NULLIF($9, ''), website), domain = COALESCE(NULLIF($10, ''), domain), + enriched_at = NOW(), updated_at = NOW() + WHERE organization_id = $1 AND id = $2`, + l.OrganizationID, l.ID, l.Email, jsonOr(l.Emails, "[]"), jsonOr(l.Socials, "{}"), jsonOr(l.Site, "{}"), + l.Phone, l.EnrichmentStatus, l.Website, l.Domain) + if err != nil { + return err + } + _, err = r.db.Exec(ctx, `UPDATE leads SET score = `+leadScoreSQL+` WHERE id = $1`, l.ID) + return err +} + +// LinkContacts records which contact each lead became. +func (r *leadFinderRepository) LinkContacts(ctx context.Context, orgID uuid.UUID, links map[uuid.UUID]uuid.UUID) error { + if len(links) == 0 { + return nil + } + leadIDs := make([]uuid.UUID, 0, len(links)) + contactIDs := make([]uuid.UUID, 0, len(links)) + for l, c := range links { + leadIDs = append(leadIDs, l) + contactIDs = append(contactIDs, c) + } + _, err := r.db.Exec(ctx, ` + UPDATE leads l SET contact_id = m.contact_id, + status = CASE WHEN l.status = 'new' THEN 'saved' ELSE l.status END, updated_at = NOW() + FROM UNNEST($2::uuid[], $3::uuid[]) AS m(lead_id, contact_id) + WHERE l.organization_id = $1 AND l.id = m.lead_id + AND EXISTS (SELECT 1 FROM contacts c WHERE c.id = m.contact_id AND c.organization_id = $1)`, + orgID, leadIDs, contactIDs) + return err +} + +// SuppressedEmails reports which addresses the organization has suppressed, +// with the same predicate the send gates use. +func (r *leadFinderRepository) SuppressedEmails(ctx context.Context, orgID uuid.UUID, emails []string) (map[string]bool, error) { + out := map[string]bool{} + if len(emails) == 0 { + return out, nil + } + rows, err := r.db.Query(ctx, `SELECT addr FROM UNNEST($2::text[]) AS a(addr) WHERE recipient_suppressed($1, addr)`, orgID, emails) + if err != nil { + return nil, err + } + defer rows.Close() + for rows.Next() { + var addr string + if err := rows.Scan(&addr); err != nil { + return nil, err + } + out[strings.ToLower(addr)] = true + } + return out, rows.Err() +} + +// --- searches --------------------------------------------------------------- + +const leadSearchColumns = `id, organization_id, created_by_user_id, name, provider, query, category, location_label, + area, saved, result_count, pages_fetched, next_cursor, last_run_at, created_at, updated_at` + +func scanLeadSearch(row pgx.Row) (models.LeadSearch, error) { + var s models.LeadSearch + var area []byte + err := row.Scan(&s.ID, &s.OrganizationID, &s.CreatedByUserID, &s.Name, &s.Provider, &s.Query, &s.Category, + &s.LocationLabel, &area, &s.Saved, &s.ResultCount, &s.PagesFetched, &s.NextCursor, &s.LastRunAt, + &s.CreatedAt, &s.UpdatedAt) + if err != nil { + return s, err + } + _ = json.Unmarshal(area, &s.Area) + s.HasMore = s.NextCursor != "" || s.PagesFetched == 0 + return s, nil +} + +func (r *leadFinderRepository) CreateSearch(ctx context.Context, s *models.LeadSearch) error { + out, err := scanLeadSearch(r.db.QueryRow(ctx, ` + INSERT INTO lead_searches (id, organization_id, created_by_user_id, name, provider, query, category, location_label, area, saved) + VALUES (COALESCE($10, gen_random_uuid()),$1,$2,$3,$4,$5,$6,$7,$8,$9) + RETURNING `+leadSearchColumns, + s.OrganizationID, s.CreatedByUserID, s.Name, s.Provider, s.Query, s.Category, s.LocationLabel, + jsonOr(s.Area, "{}"), s.Saved, nullableID(s.ID))) + if err != nil { + return err + } + *s = out + return nil +} + +func (r *leadFinderRepository) GetSearch(ctx context.Context, orgID, id uuid.UUID) (*models.LeadSearch, error) { + s, err := scanLeadSearch(r.db.QueryRow(ctx, `SELECT `+leadSearchColumns+` FROM lead_searches WHERE organization_id = $1 AND id = $2`, orgID, id)) + if isNoRows(err) { + return nil, nil + } + if err != nil { + return nil, err + } + return &s, nil +} + +func (r *leadFinderRepository) ListSearches(ctx context.Context, orgID uuid.UUID, savedOnly bool, limit int) ([]models.LeadSearch, error) { + rows, err := r.db.Query(ctx, `SELECT `+leadSearchColumns+` FROM lead_searches + WHERE organization_id = $1 AND (saved OR NOT $2) ORDER BY saved DESC, last_run_at DESC LIMIT $3`, orgID, savedOnly, limit) + if err != nil { + return nil, err + } + defer rows.Close() + out := []models.LeadSearch{} + for rows.Next() { + s, err := scanLeadSearch(rows) + if err != nil { + return nil, err + } + out = append(out, s) + } + return out, rows.Err() +} + +// RecordSearchPage stores where a search's paging stands after a fetch. +func (r *leadFinderRepository) RecordSearchPage(ctx context.Context, s *models.LeadSearch) error { + _, err := r.db.Exec(ctx, ` + UPDATE lead_searches SET + result_count = (SELECT COUNT(*) FROM lead_search_hits WHERE search_id = $2), + pages_fetched = $3, next_cursor = $4, last_run_at = NOW(), updated_at = NOW() + WHERE organization_id = $1 AND id = $2`, s.OrganizationID, s.ID, s.PagesFetched, s.NextCursor) + if err != nil { + return err + } + return r.db.QueryRow(ctx, `SELECT result_count FROM lead_searches WHERE id = $1`, s.ID).Scan(&s.ResultCount) +} + +func (r *leadFinderRepository) UpdateSearch(ctx context.Context, orgID, id uuid.UUID, name *string, saved *bool) (*models.LeadSearch, error) { + s, err := scanLeadSearch(r.db.QueryRow(ctx, ` + UPDATE lead_searches SET name = COALESCE($3, name), saved = COALESCE($4, saved), updated_at = NOW() + WHERE organization_id = $1 AND id = $2 RETURNING `+leadSearchColumns, orgID, id, name, saved)) + if isNoRows(err) { + return nil, ErrLeadSearchNotFound + } + if err != nil { + return nil, err + } + return &s, nil +} + +func (r *leadFinderRepository) DeleteSearch(ctx context.Context, orgID, id uuid.UUID) (bool, error) { + tag, err := r.db.Exec(ctx, `DELETE FROM lead_searches WHERE organization_id = $1 AND id = $2`, orgID, id) + if err != nil { + return false, err + } + return tag.RowsAffected() > 0, nil +} + +// --- enrichment runs -------------------------------------------------------- + +const leadRunColumns = `id, organization_id, requested_by_user_id, lead_ids, verify, people, status, total, processed, + emails_found, people_found, no_website, failed, credits_consumed, last_error, started_at, finished_at, created_at, updated_at` + +func scanLeadRun(row pgx.Row) (models.LeadEnrichmentRun, error) { + var run models.LeadEnrichmentRun + err := row.Scan(&run.ID, &run.OrganizationID, &run.RequestedByUserID, &run.LeadIDs, &run.Verify, &run.People, &run.Status, + &run.Total, &run.Processed, &run.EmailsFound, &run.PeopleFound, &run.NoWebsite, &run.Failed, &run.CreditsConsumed, + &run.LastError, &run.StartedAt, &run.FinishedAt, &run.CreatedAt, &run.UpdatedAt) + return run, err +} + +func (r *leadFinderRepository) CreateEnrichmentRun(ctx context.Context, run *models.LeadEnrichmentRun) error { + out, err := scanLeadRun(r.db.QueryRow(ctx, ` + INSERT INTO lead_enrichment_runs (organization_id, requested_by_user_id, lead_ids, verify, people, total) + VALUES ($1,$2,$3,$4,$5,$6) RETURNING `+leadRunColumns, + run.OrganizationID, run.RequestedByUserID, run.LeadIDs, run.Verify, run.People, run.Total)) + if err != nil { + return err + } + *run = out + return nil +} + +func (r *leadFinderRepository) GetEnrichmentRun(ctx context.Context, orgID, id uuid.UUID) (*models.LeadEnrichmentRun, error) { + run, err := scanLeadRun(r.db.QueryRow(ctx, `SELECT `+leadRunColumns+` FROM lead_enrichment_runs WHERE organization_id = $1 AND id = $2`, orgID, id)) + if isNoRows(err) { + return nil, nil + } + if err != nil { + return nil, err + } + return &run, nil +} + +// ActiveEnrichmentRuns lists the organization's unfinished runs and those that +// finished in the last minute, so a dashboard sees a run through to the end. +func (r *leadFinderRepository) ActiveEnrichmentRuns(ctx context.Context, orgID uuid.UUID) ([]models.LeadEnrichmentRun, error) { + rows, err := r.db.Query(ctx, `SELECT `+leadRunColumns+` FROM lead_enrichment_runs + WHERE organization_id = $1 AND (status IN ('queued', 'running') OR finished_at > NOW() - INTERVAL '1 minute') + ORDER BY created_at DESC LIMIT 20`, orgID) + if err != nil { + return nil, err + } + defer rows.Close() + out := []models.LeadEnrichmentRun{} + for rows.Next() { + run, err := scanLeadRun(rows) + if err != nil { + return nil, err + } + out = append(out, run) + } + return out, rows.Err() +} + +// ClaimEnrichmentRun moves a queued run, or a running one nobody has touched +// for 15 minutes, to running and returns it; nil when someone else holds it. +func (r *leadFinderRepository) ClaimEnrichmentRun(ctx context.Context, id uuid.UUID) (*models.LeadEnrichmentRun, error) { + run, err := scanLeadRun(r.db.QueryRow(ctx, ` + UPDATE lead_enrichment_runs SET status = 'running', started_at = COALESCE(started_at, NOW()), updated_at = NOW() + WHERE id = $1 AND (status = 'queued' OR (status = 'running' AND updated_at < NOW() - INTERVAL '15 minutes')) + RETURNING `+leadRunColumns, id)) + if isNoRows(err) { + return nil, nil + } + if err != nil { + return nil, err + } + return &run, nil +} + +// DueEnrichmentRuns lists runs waiting to start or abandoned mid-way. +func (r *leadFinderRepository) DueEnrichmentRuns(ctx context.Context, limit int) ([]uuid.UUID, error) { + rows, err := r.db.Query(ctx, ` + SELECT id FROM lead_enrichment_runs + WHERE (status = 'queued' AND updated_at < NOW() - INTERVAL '1 minute') + OR (status = 'running' AND updated_at < NOW() - INTERVAL '15 minutes') + ORDER BY created_at LIMIT $1`, limit) + if err != nil { + return nil, err + } + defer rows.Close() + out := []uuid.UUID{} + for rows.Next() { + var id uuid.UUID + if err := rows.Scan(&id); err != nil { + return nil, err + } + out = append(out, id) + } + return out, rows.Err() +} + +func (r *leadFinderRepository) UpdateEnrichmentProgress(ctx context.Context, run *models.LeadEnrichmentRun) error { + _, err := r.db.Exec(ctx, ` + UPDATE lead_enrichment_runs SET + processed = $2, emails_found = $3, no_website = $4, failed = $5, credits_consumed = $6, people_found = $7, + updated_at = NOW() + WHERE id = $1 AND status = 'running'`, + run.ID, run.Processed, run.EmailsFound, run.NoWebsite, run.Failed, run.CreditsConsumed, run.PeopleFound) + return err +} + +func (r *leadFinderRepository) FinishEnrichmentRun(ctx context.Context, run *models.LeadEnrichmentRun) error { + _, err := r.db.Exec(ctx, ` + UPDATE lead_enrichment_runs SET + status = $2, processed = $3, emails_found = $4, no_website = $5, failed = $6, credits_consumed = $7, + last_error = $8, people_found = $9, finished_at = NOW(), updated_at = NOW() + WHERE id = $1`, + run.ID, run.Status, run.Processed, run.EmailsFound, run.NoWebsite, run.Failed, run.CreditsConsumed, + truncateRunes(run.LastError, 500), run.PeopleFound) + if err != nil { + return err + } + // A lead the run never reached is no longer waiting on it, unless another open run holds it. + _, err = r.db.Exec(ctx, `UPDATE leads l SET enrichment_status = 'none', updated_at = NOW() + WHERE l.organization_id = $1 AND l.id = ANY($2) AND l.enrichment_status = 'queued' + AND NOT EXISTS (SELECT 1 FROM lead_enrichment_runs o WHERE o.organization_id = $1 AND o.id <> $3 + AND o.status IN ('queued', 'running') AND l.id = ANY(o.lead_ids))`, run.OrganizationID, run.LeadIDs, run.ID) + return err +} + +func nullableID(id uuid.UUID) *uuid.UUID { + if id == uuid.Nil { + return nil + } + return &id +} diff --git a/internal/repository/pg_lead_people.go b/internal/repository/pg_lead_people.go new file mode 100644 index 000000000..3deecd847 --- /dev/null +++ b/internal/repository/pg_lead_people.go @@ -0,0 +1,173 @@ +package repository + +import ( + "context" + "errors" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + + "github.com/warmbly/warmbly/internal/models" +) + +// ErrLeadPersonExists is returned when a rename lands on someone already on the lead. +var ErrLeadPersonExists = errors.New("this person is already on the lead") + +// SaveSite stores what is known about a lead's website without touching the +// rest of its enrichment. +func (r *leadFinderRepository) SaveSite(ctx context.Context, orgID, leadID uuid.UUID, site models.LeadSite) error { + _, err := r.db.Exec(ctx, `UPDATE leads SET site = $3, updated_at = NOW() WHERE organization_id = $1 AND id = $2`, + orgID, leadID, jsonOr(site, "{}")) + return err +} + +const leadPersonColumns = `id, organization_id, lead_id, name, name_key, first_name, last_name, title, seniority, email, + email_source, email_status, email_confidence, linkedin_url, phone, source, source_url, contact_id, created_at, updated_at` + +// leadPersonOrder lists the people who decide first, then those with an address. +const leadPersonOrder = `CASE seniority WHEN 'owner' THEN 0 WHEN 'executive' THEN 1 WHEN 'manager' THEN 2 ELSE 3 END, + email = '', email_confidence DESC, name` + +func scanLeadPerson(row pgx.Row) (models.LeadPerson, error) { + var p models.LeadPerson + var confidence int16 + err := row.Scan(&p.ID, &p.OrganizationID, &p.LeadID, &p.Name, &p.NameKey, &p.FirstName, &p.LastName, &p.Title, + &p.Seniority, &p.Email, &p.EmailSource, &p.EmailStatus, &confidence, &p.LinkedInURL, &p.Phone, &p.Source, + &p.SourceURL, &p.ContactID, &p.CreatedAt, &p.UpdatedAt) + p.EmailConfidence = int(confidence) + return p, err +} + +func (r *leadFinderRepository) PeopleForLeads(ctx context.Context, orgID uuid.UUID, leadIDs []uuid.UUID) (map[uuid.UUID][]models.LeadPerson, error) { + out := map[uuid.UUID][]models.LeadPerson{} + if len(leadIDs) == 0 { + return out, nil + } + rows, err := r.db.Query(ctx, `SELECT `+leadPersonColumns+` FROM lead_people + WHERE organization_id = $1 AND lead_id = ANY($2) ORDER BY lead_id, `+leadPersonOrder, orgID, leadIDs) + if err != nil { + return nil, err + } + defer rows.Close() + for rows.Next() { + p, err := scanLeadPerson(rows) + if err != nil { + return nil, err + } + out[p.LeadID] = append(out[p.LeadID], p) + } + return out, rows.Err() +} + +func (r *leadFinderRepository) GetPerson(ctx context.Context, orgID, leadID, id uuid.UUID) (*models.LeadPerson, error) { + p, err := scanLeadPerson(r.db.QueryRow(ctx, `SELECT `+leadPersonColumns+` FROM lead_people + WHERE organization_id = $1 AND lead_id = $2 AND id = $3`, orgID, leadID, id)) + if isNoRows(err) { + return nil, nil + } + if err != nil { + return nil, err + } + return &p, nil +} + +// SavePeople writes a lead's people. A person with an id is updated as given; +// anyone else is inserted, or merged onto the row already holding their name +// without overwriting what a teammate typed in. Returns ErrLeadNotFound when +// the lead is not the organization's. +func (r *leadFinderRepository) SavePeople(ctx context.Context, orgID, leadID uuid.UUID, people []models.LeadPerson) ([]models.LeadPerson, error) { + tx, err := r.db.Begin(ctx) + if err != nil { + return nil, err + } + defer func() { _ = tx.Rollback(ctx) }() + var owned bool + if err := tx.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM leads WHERE organization_id = $1 AND id = $2)`, orgID, leadID).Scan(&owned); err != nil { + return nil, err + } + if !owned { + return nil, ErrLeadNotFound + } + out := make([]models.LeadPerson, 0, len(people)) + for _, p := range people { + if p.NameKey == "" || p.Name == "" { + continue + } + args := []any{orgID, leadID, truncateRunes(p.Name, 120), truncateRunes(p.NameKey, 120), truncateRunes(p.FirstName, 60), + truncateRunes(p.LastName, 60), truncateRunes(p.Title, 120), p.Seniority, truncateRunes(p.Email, 254), p.EmailSource, + p.EmailStatus, p.EmailConfidence, truncateRunes(p.LinkedInURL, 300), truncateRunes(p.Phone, 40), p.Source, + truncateRunes(p.SourceURL, 500)} + var saved models.LeadPerson + if p.ID != uuid.Nil { + saved, err = scanLeadPerson(tx.QueryRow(ctx, ` + UPDATE lead_people SET name = $3, name_key = $4, first_name = $5, last_name = $6, title = $7, seniority = $8, + email = $9, email_source = $10, email_status = $11, email_confidence = $12, linkedin_url = $13, phone = $14, + source = $15, source_url = $16, updated_at = NOW() + WHERE organization_id = $1 AND lead_id = $2 AND id = $17 + RETURNING `+leadPersonColumns, append(args, p.ID)...)) + } else { + // A typed-in address is never replaced; a guess gives way to anything firmer. + saved, err = scanLeadPerson(tx.QueryRow(ctx, ` + INSERT INTO lead_people AS cur (organization_id, lead_id, name, name_key, first_name, last_name, title, seniority, + email, email_source, email_status, email_confidence, linkedin_url, phone, source, source_url) + VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16) + ON CONFLICT (lead_id, name_key) DO UPDATE SET + title = CASE WHEN cur.title = '' THEN EXCLUDED.title ELSE cur.title END, + seniority = CASE WHEN cur.title = '' THEN EXCLUDED.seniority ELSE cur.seniority END, + email = CASE WHEN `+replaceEmailSQL+` THEN EXCLUDED.email ELSE cur.email END, + email_source = CASE WHEN `+replaceEmailSQL+` THEN EXCLUDED.email_source ELSE cur.email_source END, + email_status = CASE WHEN `+replaceEmailSQL+` THEN EXCLUDED.email_status ELSE cur.email_status END, + email_confidence = CASE WHEN `+replaceEmailSQL+` THEN EXCLUDED.email_confidence ELSE cur.email_confidence END, + linkedin_url = COALESCE(NULLIF(cur.linkedin_url, ''), EXCLUDED.linkedin_url), + phone = COALESCE(NULLIF(cur.phone, ''), EXCLUDED.phone), + source_url = COALESCE(NULLIF(cur.source_url, ''), EXCLUDED.source_url), + updated_at = NOW() + RETURNING `+leadPersonColumns, args...)) + } + if isNoRows(err) { + continue + } + var pgErr *pgconn.PgError + if errors.As(err, &pgErr) && pgErr.Code == "23505" { + return nil, ErrLeadPersonExists + } + if err != nil { + return nil, err + } + out = append(out, saved) + } + return out, tx.Commit(ctx) +} + +// replaceEmailSQL decides whether an incoming address takes over a stored one. +const replaceEmailSQL = `EXCLUDED.email <> '' AND cur.email_source <> 'manual' AND (cur.email = '' + OR (cur.email_source = 'pattern' AND (EXCLUDED.email_source <> 'pattern' OR EXCLUDED.email_confidence >= cur.email_confidence)))` + +func (r *leadFinderRepository) DeletePerson(ctx context.Context, orgID, leadID, id uuid.UUID) (bool, error) { + tag, err := r.db.Exec(ctx, `DELETE FROM lead_people WHERE organization_id = $1 AND lead_id = $2 AND id = $3`, orgID, leadID, id) + if err != nil { + return false, err + } + return tag.RowsAffected() > 0, nil +} + +// LinkPersonContacts records which contact each person became. +func (r *leadFinderRepository) LinkPersonContacts(ctx context.Context, orgID uuid.UUID, links map[uuid.UUID]uuid.UUID) error { + if len(links) == 0 { + return nil + } + personIDs := make([]uuid.UUID, 0, len(links)) + contactIDs := make([]uuid.UUID, 0, len(links)) + for p, c := range links { + personIDs = append(personIDs, p) + contactIDs = append(contactIDs, c) + } + _, err := r.db.Exec(ctx, ` + UPDATE lead_people p SET contact_id = m.contact_id, updated_at = NOW() + FROM UNNEST($2::uuid[], $3::uuid[]) AS m(person_id, contact_id) + WHERE p.organization_id = $1 AND p.id = m.person_id + AND EXISTS (SELECT 1 FROM contacts c WHERE c.id = m.contact_id AND c.organization_id = $1)`, + orgID, personIDs, contactIDs) + return err +} diff --git a/qa/fixtures/lead-finder.sql b/qa/fixtures/lead-finder.sql new file mode 100644 index 000000000..bbb3fd51c --- /dev/null +++ b/qa/fixtures/lead-finder.sql @@ -0,0 +1,132 @@ +-- Lead finder leads and a saved search for the isolated rich-seed QA database, never production. +BEGIN; +DO $$ +BEGIN + IF left(current_database(), 11) <> 'warmbly_qa_' THEN + RAISE EXCEPTION 'lead finder proof fixtures require an isolated warmbly_qa_ database'; + END IF; + IF NOT EXISTS (SELECT 1 FROM organizations WHERE id = '22222222-0000-0000-0000-000000000001') THEN + RAISE EXCEPTION 'lead finder proof fixtures require the rich QA seed'; + END IF; +END $$; + +DELETE FROM lead_enrichment_runs WHERE organization_id = '22222222-0000-0000-0000-000000000001' AND id::text LIKE '86300000-%'; +DELETE FROM lead_searches WHERE organization_id = '22222222-0000-0000-0000-000000000001' AND id::text LIKE '86300000-%'; +DELETE FROM leads WHERE organization_id = '22222222-0000-0000-0000-000000000001' AND id::text LIKE '86300000-%'; + +INSERT INTO lead_searches (id, organization_id, created_by_user_id, name, provider, query, category, location_label, area, saved, result_count, pages_fetched) +VALUES ('86300000-0000-0000-0000-000000000000', '22222222-0000-0000-0000-000000000001', '11111111-0000-0000-0000-000000000001', + 'Dentists in downtown Austin', 'osm', '', 'dentist', 'Austin, Texas', + '{"kind":"circle","center":{"lat":30.2672,"lng":-97.7431},"radius_m":4500,"bounds":{"south":30.2267,"west":-97.79,"north":30.3077,"east":-97.6962}}', + true, 36, 1); + +-- Synthetic businesses on the reserved .example TLD, so no address or site is real. +WITH names(n, name) AS ( + SELECT n, (ARRAY['Bright Smiles Dental','Congress Avenue Dentistry','Lady Bird Family Dental','Barton Springs Orthodontics', + 'Rainey Street Smiles','Zilker Dental Studio','East Sixth Dental','Clarksville Dental Care','Bouldin Creek Dentistry', + 'Travis Heights Dental','Mueller Family Dentistry','Hyde Park Dental Arts','Riverside Dental Group','South Lamar Smiles', + 'Capitol View Dental','Pease Park Pediatric Dentistry','Shoal Creek Dental','Seaholm Dental Loft','Red River Dental', + 'Cherrywood Dental','Holly Street Dental','Tarrytown Dental Office','Market District Dentistry','Colorado River Dental', + 'Waterloo Dental Spa','Old Pecan Dental','Willow Creek Implants','Guadalupe Dental','Rosewood Dental Clinic', + 'Brazos Street Dental','Lamar Union Dentistry','Saltillo Smiles','Downtown Austin Endodontics','Treaty Oak Dental', + 'Blue Bonnet Dental','Moonlight Tower Dentistry'])[n] + FROM generate_series(1, 36) AS n +) +INSERT INTO leads (id, organization_id, provider, external_id, name, category, categories, address, street, city, region, postcode, country, + latitude, longitude, phone, website, domain, email, emails, socials, rating, review_count, hours, business_status, + maps_url, site, status, enrichment_status, enriched_at, tags, notes, first_seen_at, last_seen_at) +SELECT ('86300000-0000-0000-0000-' || lpad(n::text, 12, '0'))::uuid, + '22222222-0000-0000-0000-000000000001', 'osm', 'node/86300' || n, name, 'Dentist', ARRAY['Dentist'], + (100 + n * 7) || ' ' || (ARRAY['Congress Ave','E 6th St','S Lamar Blvd','Guadalupe St','W 5th St','Red River St'])[1 + n % 6] || ', Austin, TX 787' || lpad((n % 40)::text, 2, '0'), + (100 + n * 7) || ' ' || (ARRAY['Congress Ave','E 6th St','S Lamar Blvd','Guadalupe St','W 5th St','Red River St'])[1 + n % 6], + 'Austin', 'TX', '787' || lpad((n % 40)::text, 2, '0'), 'US', + 30.2672 + 0.028 * sin(n * 12.9898), -97.7431 + 0.034 * cos(n * 78.233), + CASE WHEN n % 5 = 0 THEN '' ELSE '+1 512 555 0' || lpad(n::text, 3, '0') END, + CASE WHEN n % 4 = 3 THEN '' ELSE 'https://' || lower(replace(name, ' ', '')) || '.example' END, + CASE WHEN n % 4 = 3 THEN '' ELSE lower(replace(name, ' ', '')) || '.example' END, + CASE WHEN n % 4 = 3 OR n % 7 = 0 THEN '' ELSE (ARRAY['info','hello','frontdesk','office'])[1 + n % 4] || '@' || lower(replace(name, ' ', '')) || '.example' END, + CASE WHEN n % 4 = 3 OR n % 7 = 0 THEN '[]'::jsonb ELSE jsonb_build_array( + jsonb_build_object('email', (ARRAY['info','hello','frontdesk','office'])[1 + n % 4] || '@' || lower(replace(name, ' ', '')) || '.example', + 'source', 'website', 'url', 'https://' || lower(replace(name, ' ', '')) || '.example/contact', + 'domain_match', true, 'status', CASE WHEN n % 6 = 1 THEN 'risky' ELSE 'valid' END), + jsonb_build_object('email', 'dr.' || lower(split_part(name, ' ', 1)) || '@' || lower(replace(name, ' ', '')) || '.example', + 'source', 'website', 'url', 'https://' || lower(replace(name, ' ', '')) || '.example/team', + 'domain_match', true, 'status', 'unknown')) END, + CASE WHEN n % 3 = 0 THEN '{}'::jsonb ELSE jsonb_build_object('facebook', 'https://www.facebook.com/' || lower(replace(name, ' ', '')), + 'instagram', 'https://www.instagram.com/' || lower(replace(name, ' ', ''))) END, + round((3.4 + (n % 17) * 0.095)::numeric, 1)::float8, 8 + (n * 37) % 640, + '["Mo-Fr 08:00-17:00", "Sa 09:00-13:00"]'::jsonb, 'operational', + 'https://www.openstreetmap.org/node/86300' || n, + CASE WHEN n % 4 = 3 THEN '{}'::jsonb ELSE jsonb_build_object( + 'reachable', true, 'https', n % 5 <> 2, 'final_url', 'https://' || lower(replace(name, ' ', '')) || '.example/', + 'title', name || ' | Family and cosmetic dentistry in Austin', + 'description', 'Gentle, modern dental care in the heart of Austin. New patients welcome.', + 'platform', (ARRAY['WordPress','Wix','Squarespace','Webflow'])[1 + n % 4], + 'signals', CASE WHEN n % 5 = 2 THEN '["No HTTPS", "Not mobile friendly", "Outdated footer (2019)", "No analytics"]'::jsonb + ELSE '["Google Analytics", "Online booking", "Contact form"]'::jsonb END, + 'pages', 3, 'checked_at', '2026-11-03T15:00:00Z') END, + (ARRAY['new','new','new','saved','contacted','new'])[1 + n % 6], + CASE WHEN n % 4 = 3 THEN 'no_website' ELSE 'done' END, + CASE WHEN n % 4 = 3 THEN NULL ELSE NOW() - INTERVAL '1 day' END, + CASE WHEN n % 8 = 0 THEN ARRAY['implants'] ELSE '{}'::text[] END, + '', NOW() - (n || ' minutes')::interval, NOW() - (n || ' minutes')::interval +FROM names; + +UPDATE leads SET score = LEAST(100, + (CASE WHEN website <> '' THEN 15 ELSE 0 END) + + (CASE WHEN email <> '' THEN 25 ELSE 0 END) + + (CASE WHEN EXISTS (SELECT 1 FROM jsonb_array_elements(emails) e WHERE e->>'email' = email AND e->>'status' = 'valid') THEN 15 ELSE 0 END) + + (CASE WHEN phone <> '' THEN 15 ELSE 0 END) + + (CASE WHEN socials <> '{}'::jsonb THEN 10 ELSE 0 END) + + (CASE WHEN rating >= 4 THEN 10 WHEN rating >= 3 THEN 5 ELSE 0 END) + + (CASE WHEN review_count >= 25 THEN 10 WHEN review_count >= 5 THEN 5 ELSE 0 END)) +WHERE id::text LIKE '86300000-%'; + +-- Synthetic people at the businesses with a website, with addresses on each domain's pattern. +WITH roster AS ( + SELECT l.id AS lead_id, right(l.id::text, 12)::int AS n, l.domain, k + FROM leads l, generate_series(1, 3) AS k + WHERE l.id::text LIKE '86300000-%' AND l.domain <> '' AND k <= 1 + right(l.id::text, 12)::int % 3 +), named AS ( + SELECT lead_id, n, domain, k, + (ARRAY['Elena','Marcus','Priya','Sofia','Daniel','Grace','Omar','Hannah','Luis','Maya','Ethan','Chloe','Nora','Caleb','Ava','Theo'])[1 + (n * 3 + k * 5) % 16] AS first, + (ARRAY['Morales','Bennett','Shah','Nguyen','Carter','Kim','Haddad','Fischer','Ortiz','Reyes','Walsh','Park','Lindqvist','Brooks','Okafor','Romano'])[1 + (n * 7 + k * 3) % 16] AS last, + (ARRAY['Owner & Lead Dentist','Practice Manager','Associate Dentist'])[k] AS title, + (ARRAY['owner','manager','staff'])[k] AS seniority + FROM roster +) +INSERT INTO lead_people (organization_id, lead_id, name, name_key, first_name, last_name, title, seniority, email, email_source, + email_status, email_confidence, source, source_url) +SELECT '22222222-0000-0000-0000-000000000001', lead_id, first || ' ' || last, lower(first || ' ' || last), first, last, title, seniority, + CASE WHEN k = 3 AND n % 2 = 1 THEN '' + ELSE lower(first) || CASE WHEN n % 2 = 0 THEN '.' || lower(last) ELSE '' END || '@' || domain END, + CASE WHEN k = 3 AND n % 2 = 1 THEN '' WHEN k = 1 AND n % 3 = 1 THEN 'website' ELSE 'pattern' END, + CASE WHEN k = 3 AND n % 2 = 1 THEN '' WHEN k = 1 AND n % 3 = 1 THEN 'valid' WHEN n % 5 = 1 THEN 'guessed' ELSE 'valid' END, + CASE WHEN k = 3 AND n % 2 = 1 THEN 0 WHEN k = 1 AND n % 3 = 1 THEN 100 WHEN n % 5 = 1 THEN 60 ELSE 95 END, + CASE WHEN k = 3 THEN 'schema' ELSE 'page' END, + 'https://' || domain || '/our-team' +FROM named; + +UPDATE leads SET site = site || jsonb_build_object('email_pattern', CASE WHEN right(id::text, 12)::int % 2 = 0 THEN 'first.last' ELSE 'first' END) +WHERE id::text LIKE '86300000-%' AND domain <> ''; + +INSERT INTO lead_search_hits (search_id, lead_id) +SELECT '86300000-0000-0000-0000-000000000000', id FROM leads WHERE id::text LIKE '86300000-%'; + +-- One website the listing lacked, worked out from the name. +UPDATE leads SET site = site || '{"found_website": true}'::jsonb WHERE id = '86300000-0000-0000-0000-000000000002'; + +-- A website run part way through: four businesses still being read. The backend leaves a +-- running run alone for 15 minutes, longer than a recording takes. +UPDATE leads SET enrichment_status = 'queued' +WHERE id IN ('86300000-0000-0000-0000-000000000004', '86300000-0000-0000-0000-000000000006', + '86300000-0000-0000-0000-000000000009', '86300000-0000-0000-0000-000000000010'); +INSERT INTO lead_enrichment_runs (id, organization_id, requested_by_user_id, lead_ids, status, total, processed, emails_found, people_found, started_at) +SELECT '86300000-0000-0000-0000-0000000e0001', '22222222-0000-0000-0000-000000000001', '11111111-0000-0000-0000-000000000001', + array_agg(id ORDER BY id), 'running', 12, 7, 5, 6, NOW() +FROM leads WHERE id::text LIKE '86300000-%' AND right(id::text, 12)::int BETWEEN 1 AND 12; + +-- The product tour would cover the page; the flow records the lead finder, not the tour. +UPDATE users SET product_tour_completed_at = now() +WHERE id = '11111111-0000-0000-0000-000000000001' AND product_tour_completed_at IS NULL; +COMMIT; diff --git a/qa/flows/lead-finder.flow.ts b/qa/flows/lead-finder.flow.ts new file mode 100644 index 000000000..612c98939 --- /dev/null +++ b/qa/flows/lead-finder.flow.ts @@ -0,0 +1,151 @@ +import { expect, test } from "../lib/proof.ts"; + +// Requires ../fixtures/lead-finder.sql applied to this worktree's rich-seed database. +const FIXTURES = process.env.QA_LEAD_FINDER_FIXTURES === "1"; + +test.describe("lead finder", () => { + test.skip(!FIXTURES, "Apply qa/fixtures/lead-finder.sql to this stack's database and set QA_LEAD_FINDER_FIXTURES=1."); + + test("open a saved search on the map, restyle the pins and read one business's details", async ({ page, proof }) => { + await page.goto("/app/leads"); + await expect(page.getByRole("heading", { name: "Lead finder" })).toBeVisible(); + await proof.chapter("Lead finder", "Local businesses on a map, enriched from their own websites"); + + await page.getByText("Dentists in downtown Austin").click(); + await expect(page.getByText("Bright Smiles Dental").first()).toBeVisible(); + await expect(page.getByText(/36 on map/)).toBeVisible(); + await proof.dwell(); + await proof.shot("saved-search", { caption: "A saved search: its area on the map, pins colored by how each business can be reached, the list sorted best first" }); + + await page.getByRole("button", { name: "List", exact: true }).click(); + await expect(page.getByText("Finding people and emails")).toBeVisible(); + await expect(page.getByText("Reading the website").first()).toBeVisible(); + await proof.dwell(); + await proof.shot("list-progress", { caption: "A website run going in the background: progress above the list, and each business being read marked in its row" }); + await page.getByRole("button", { name: "Split", exact: true }).click(); + + await page.getByRole("button", { name: "Map layers" }).click(); + await page.getByRole("menuitem", { name: "Score" }).click(); + await expect(page.getByText("100", { exact: true }).last()).toBeVisible(); + await page.getByRole("button", { name: "Map layers" }).click(); + await page.getByRole("menuitem", { name: "Heatmap" }).click(); + await expect(page.getByText("Brighter where leads are denser and better")).toBeVisible(); + await proof.dwell(); + await proof.shot("heatmap", { caption: "The same leads as a heatmap weighted by score" }); + await page.getByRole("button", { name: "Map layers" }).click(); + await page.getByRole("menuitem", { name: "Pins" }).click(); + + await page.getByText("Bright Smiles Dental").first().click(); + const drawer = page.getByRole("complementary", { name: "Lead details" }); + await expect(drawer.getByRole("heading", { name: "Bright Smiles Dental" })).toBeVisible(); + await expect(drawer.getByText("Primary")).toBeVisible(); + await proof.dwell(); + await proof.shot("lead-details", { caption: "A lead's addresses with their verification, phone, address, rating, socials and hours" }); + + await drawer.getByRole("button", { name: "Website" }).click(); + await expect(drawer.getByText(/Built with/)).toBeVisible(); + await proof.dwell(); + await proof.shot("lead-website", { caption: "What reading the website found: platform, HTTPS and the gaps worth pitching" }); + await drawer.getByRole("button", { name: "Close" }).click(); + }); + + test("filter to verified, well rated leads, select them and export or add them to contacts", async ({ page, proof }) => { + await page.goto("/app/leads"); + await page.getByText("Dentists in downtown Austin").click(); + await expect(page.getByText("Bright Smiles Dental").first()).toBeVisible(); + await proof.chapter("Refine and act", "Filter the list, then work the whole selection at once"); + + await page.getByRole("button", { name: "Has email" }).click(); + await page.getByRole("button", { name: "4+", exact: true }).click(); + await expect(page.getByText(/\d+ leads?$/).first()).toBeVisible(); + await proof.dwell(); + await proof.shot("filtered", { caption: "Only leads with an email and four stars or more, on the map and in the list" }); + + await page.getByRole("button", { name: /^Filters/ }).click(); + await expect(page.getByRole("dialog", { name: "Filters" }).getByText("Reachability")).toBeVisible(); + await proof.dwell(); + await proof.shot("filter-panel", { caption: "Every other filter one click away above the results, no switching away from the search" }); + await page.keyboard.press("Escape"); + + await page.getByRole("checkbox", { name: "Select every lead on screen" }).check(); + await expect(page.getByText(/selected$/)).toBeVisible(); + await proof.shot("selection-bar", { caption: "Find emails, add to contacts, export, tag, set a status or delete, for the whole selection" }); + + await page.getByRole("button", { name: "Export" }).click(); + const exportDialog = page.getByRole("dialog", { name: /leads?$/ }); + await expect(exportDialog.getByText("Columns", { exact: true })).toBeVisible(); + await proof.dwell(); + await proof.shot("export-dialog", { caption: "Export as CSV, Excel or JSON with the columns you pick" }); + await exportDialog.getByRole("button", { name: "Cancel" }).click(); + + await page.getByRole("button", { name: "Add to contacts" }).click(); + const addDialog = page.getByRole("dialog", { name: /leads?$/ }); + await expect(addDialog.getByText("Only verified addresses")).toBeVisible(); + await expect(addDialog.getByText("Segments", { exact: true })).toBeVisible(); + await expect(addDialog.getByText("Contacts you already have")).toBeVisible(); + await proof.dwell(); + await proof.shot("add-to-contacts", { caption: "Add the selection to contacts, with segments, labels and campaigns in the same step, and what to do with contacts you already have" }); + await addDialog.getByRole("button", { name: "Cancel" }).click(); + }); + + test("see who runs a business, ask for someone's email and pick where businesses come from", async ({ page, proof }) => { + await page.goto("/app/leads"); + await page.getByText("Dentists in downtown Austin").click(); + await expect(page.getByText("Bright Smiles Dental").first()).toBeVisible(); + await proof.chapter("People", "Who runs each business, and how to reach them"); + + await page.getByText("Bright Smiles Dental").first().click(); + const drawer = page.getByRole("complementary", { name: "Lead details" }); + await expect(drawer.getByText("Decision makers")).toBeVisible(); + await drawer.getByRole("button", { name: /^People/ }).click(); + await expect(drawer.getByText("Owner & Lead Dentist")).toBeVisible(); + await expect(drawer.getByText("Confirmed").first()).toBeVisible(); + await proof.dwell(); + await proof.shot("lead-people", { caption: "The people the website names, most senior first, with each address and how far to trust it" }); + + await drawer.getByRole("textbox", { name: "First name" }).last().pressSequentially("Ava", { delay: 60 }); + await drawer.getByRole("textbox", { name: "Last name" }).last().pressSequentially("Romano", { delay: 60 }); + await drawer.getByRole("textbox", { name: "Title (optional)" }).pressSequentially("Office manager", { delay: 40 }); + await expect(drawer.getByRole("button", { name: "Find email" })).toBeEnabled(); + await proof.dwell(); + await proof.shot("find-someone", { caption: "Name anyone at the business and their address is worked out from the domain and checked" }); + await drawer.getByRole("button", { name: "Close" }).click(); + + await page.getByRole("button", { name: /OpenStreetMap/ }).click(); + await expect(page.getByRole("menuitem", { name: /Google Places/ })).toBeVisible(); + await proof.dwell(); + await proof.shot("source-picker", { caption: "Every source with its logo and what it costs; the keyed ones link to Integrations" }); + await page.keyboard.press("Escape"); + }); + + test("pick a category, go to a city and draw the exact area to search", async ({ page, proof }) => { + await page.goto("/app/leads"); + await expect(page.getByRole("heading", { name: "Lead finder" })).toBeVisible(); + await proof.chapter("A new search", "What, where, and the exact area"); + + await page.getByRole("button", { name: "Restaurants" }).click(); + await page.getByRole("button", { name: /^All \d+ categories/ }).click(); + await expect(page.getByPlaceholder("Search categories…")).toBeVisible(); + await page.getByPlaceholder("Search categories…").pressSequentially("vet", { delay: 60 }); + await page.getByRole("menuitem", { name: "Veterinarians" }).click(); + + await page.getByRole("textbox", { name: "Location" }).pressSequentially("Austin, Tex", { delay: 60 }); + await page.getByRole("option", { name: /Austin/ }).first().click(); + await expect(page.getByText("The visible map, or draw an area")).toBeVisible(); + + await page.getByRole("button", { name: "Draw a circle to search" }).click(); + await expect(page.getByText("Drag from the center outwards")).toBeVisible(); + const map = page.locator(".maplibregl-canvas"); + const box = await map.boundingBox(); + if (!box) throw new Error("map canvas has no size"); + const cx = box.x + box.width / 2; + const cy = box.y + box.height / 2; + await page.mouse.move(cx, cy); + await page.mouse.down(); + await page.mouse.move(cx + 140, cy + 40, { steps: 12 }); + await page.mouse.up(); + await expect(page.getByText(/^Circle, /)).toBeVisible(); + await proof.dwell(); + await proof.shot("draw-area", { caption: "A drawn circle becomes the search area; the source and its cost are picked below" }); + }); +}); diff --git a/web/package.json b/web/package.json index a5e3b8033..9aad6989f 100644 --- a/web/package.json +++ b/web/package.json @@ -89,6 +89,7 @@ "immer": "^11.1.18", "input-otp": "^1.5.0", "lucide-react": "^0.563.0", + "maplibre-gl": "^5.24.0", "motion": "^12.43.0", "next-themes": "^0.4.6", "papaparse": "^5.7.0", diff --git a/web/pnpm-lock.yaml b/web/pnpm-lock.yaml index a228b753a..f5e7eaf3a 100644 --- a/web/pnpm-lock.yaml +++ b/web/pnpm-lock.yaml @@ -231,6 +231,9 @@ importers: lucide-react: specifier: ^0.563.0 version: 0.563.0(react@19.3.0) + maplibre-gl: + specifier: ^5.24.0 + version: 5.24.0 motion: specifier: ^12.43.0 version: 12.43.0(react-dom@19.3.0(react@19.3.0))(react@19.3.0) @@ -861,6 +864,42 @@ packages: peerDependencies: solid-js: ^1.8.8 + '@mapbox/jsonlint-lines-primitives@2.0.3': + resolution: {integrity: sha512-0SElaV0uMxEnxzBhhX9WTuPyUeMsAN/SS0i16tjuba4/mio63MG9khjC1a0JAiPGXAwvwm4UfHJURCN7nyudQg==} + engines: {node: '>= 22'} + + '@mapbox/point-geometry@1.1.0': + resolution: {integrity: sha512-YGcBz1cg4ATXDCM/71L9xveh4dynfGmcLDqufR+nQQy3fKwsAZsWd/x4621/6uJaeB9mwOHE6hPeDgXz9uViUQ==} + + '@mapbox/tiny-sdf@2.3.0': + resolution: {integrity: sha512-gBvcNDBBB66bgQYvnaJ6Jk+VCaMmVq5+IZR2kWPisT88Z8s0kBQt6hfVi8QgRW8Vpg0UWZzBA4ZSyzHHC+VeRA==} + + '@mapbox/unitbezier@0.0.1': + resolution: {integrity: sha512-nMkuDXFv60aBr9soUG5q+GvZYL+2KZHVvsqFCzqnkGEf46U2fvmytHaEVc1/YZbiLn8X+eR3QzX1+dwDO1lxlw==} + + '@mapbox/unitbezier@1.0.0': + resolution: {integrity: sha512-fqd515fjBmANKGGsQ286E2Wvj/XvDFpGzwJxq4CI6jMQue6Oy04uCKp+JWKF00xRTmk6cEu1jPJ9p3xqH8YWqQ==} + + '@mapbox/vector-tile@2.0.5': + resolution: {integrity: sha512-pXj8m7KTsqZt+1jsE0xIpGvqTSbblfkuEJL/NJmNePMtEwxO8V3XMDo9WMSfDeqHvCtBI9Lmt4mGcGR10zecmw==} + + '@mapbox/whoots-js@3.1.0': + resolution: {integrity: sha512-Es6WcD0nO5l+2BOQS4uLfNPYQaNDfbot3X1XUoloz+x0mPDS3eeORZJl06HXjwBG1fOGwCRnzK88LMdxKRrd6Q==} + engines: {node: '>=6.0.0'} + + '@maplibre/geojson-vt@6.3.0': + resolution: {integrity: sha512-3Zw2jsU9pIJG3G2CQFbLjWj2MlAHodhD7cSY+15iywUuLmmkgzcKRnueVRZ4AcC/5wOtfhidcJAAzBpoBNs3Xg==} + + '@maplibre/maplibre-gl-style-spec@24.10.0': + resolution: {integrity: sha512-lichxSiagMEBBrqHF0trtMQH9RKh+9jUlIJl0qW0QHvt2H/tbvUWdE+ZzI2Jd0/pT7j/iavLonlPu7EQ/ixTOw==} + hasBin: true + + '@maplibre/mlt@1.3.0': + resolution: {integrity: sha512-7M2O7ABM80Oi8XPkfkrjKB8mOBIxGoVgkA52Mu4RMWoBvvMdagQ522+WxVYujZsMpqIr3BpzrTbXrm4k8lCzCQ==} + + '@maplibre/vt-pbf@4.3.3': + resolution: {integrity: sha512-dEe5XUd64RQbxNxy2OzIkJnwNDWjVmSXjCd0A7zLirm7QJ/WWbmtDFIkfsiM4yt1cplqzG6oSivRYeWx1SM1yg==} + '@napi-rs/lzma-linux-x64-gnu@1.5.1': resolution: {integrity: sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==} engines: {node: ^22.20 || ^24.12 || >=25} @@ -2054,6 +2093,9 @@ packages: '@types/estree@1.0.9': resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==} + '@types/geojson@7946.0.16': + resolution: {integrity: sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==} + '@types/json-schema@7.0.15': resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==} @@ -2407,6 +2449,9 @@ packages: resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==} engines: {node: '>= 0.4'} + earcut@3.2.4: + resolution: {integrity: sha512-FHc6yNpnTORB0tM5kmZ03iD2mDuNakDE2lvf4Hw1XkfxtEHIGVi01B/GqUSwx+NcC1WGjidAfpTXzeALtPtfpg==} + electron-to-chromium@1.5.431: resolution: {integrity: sha512-AAVihz2YwJeOdAynX8MUtqpvjY0gaiARp/7+r4kwqgzqXMrfG1qDN7vwT80uxAoOQRPcZH8t73EI+CA/1OJN8A==} @@ -2610,6 +2655,9 @@ packages: resolution: {integrity: sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==} engines: {node: '>= 0.4'} + gl-matrix@3.4.4: + resolution: {integrity: sha512-latSnyDNt/8zYUB6VIJ6PCh2jBjJX6gnDsoCZ7LyW7GkqrD51EWwa9qCoGixj8YqBtETQK/xY7OmpTF8xz1DdQ==} + glob-parent@6.0.2: resolution: {integrity: sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==} engines: {node: '>=10.13.0'} @@ -2772,11 +2820,17 @@ packages: json-stable-stringify-without-jsonify@1.0.1: resolution: {integrity: sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==} + json-stringify-pretty-compact@4.0.0: + resolution: {integrity: sha512-3CNZ2DnrpByG9Nqj6Xo8vqbjT4F6N+tb4Gb28ESAZjYZ5yqvmc56J+/kuIwkaAMOyblTQhUW7PxMkUb8Q36N3Q==} + json5@2.2.3: resolution: {integrity: sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==} engines: {node: '>=6'} hasBin: true + kdbush@4.1.0: + resolution: {integrity: sha512-e9vurzrXJQrFX6ckpHP3bvj5l+9CnYzkxDNnNQ1h2QTqdWsUAJgXiKdGNcOa1EY85dU8KbQ+z/FdQdB7P+9yfQ==} + keyv@4.5.4: resolution: {integrity: sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==} @@ -2894,6 +2948,10 @@ packages: resolution: {integrity: sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==} engines: {node: '>=10'} + maplibre-gl@5.24.0: + resolution: {integrity: sha512-ALyFxgtd5R+65UqZ/++lOqwWcC0SNho9c27fYSyLmG7AfnAul2o46F05aDJGPbFU57wos9dgcIySHs0Xe6ia3A==} + engines: {node: '>=16.14.0', npm: '>=8.1.0'} + math-intrinsics@1.1.0: resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==} engines: {node: '>= 0.4'} @@ -2920,6 +2978,9 @@ packages: minimatch@3.1.5: resolution: {integrity: sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==} + minimist@1.2.8: + resolution: {integrity: sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==} + minipass@7.1.3: resolution: {integrity: sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==} engines: {node: '>=16 || 14 >=14.17'} @@ -2947,6 +3008,9 @@ packages: ms@2.1.3: resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} + murmurhash-js@1.0.0: + resolution: {integrity: sha512-TvmkNhkv8yct0SVBSy+o8wYzXjE4Zz3PCesbfs8HiCXXdcTuocApFv11UWlNFWKYsP2okqrhb7JNlSm9InBhIw==} + nanoid@3.3.20: resolution: {integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==} engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} @@ -3018,6 +3082,14 @@ packages: pathe@2.0.3: resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==} + pbf@4.0.2: + resolution: {integrity: sha512-J0ajxARhZfpUEebxYs1vhMGMuLSXtBe1e+fFPDrf2uA2hgo+UshKfNUWOz92HJNz6/NFEXseQPddnHkTreWRqg==} + hasBin: true + + pbf@5.1.2: + resolution: {integrity: sha512-mnvGdvOrIvJOBGUEdGkrVXjN8E/VkIJCkf2eS1DH2yv82ORUlLttmDt0rWY38yYZmVwciZwBUvHM20qxBZf40w==} + hasBin: true + picocolors@1.1.1: resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} @@ -3040,6 +3112,9 @@ packages: react: optional: true + potpack@2.1.0: + resolution: {integrity: sha512-pcaShQc1Shq0y+E7GqJqvZj8DTthWV1KeHGdi0Z6IAin2Oi3JnLCOfwnCo84qc+HAp52wT9nK9H7FAJp5a44GQ==} + preact@10.29.8: resolution: {integrity: sha512-ej2aVZ+vZ8WO7tvlQWRM9N63A0KzF9q4mWJfDUHgYaIofWY9hu74QdnQrjoPMmZi2/nZ5gN0bJCQF49xQqx09Q==} peerDependencies: @@ -3099,6 +3174,9 @@ packages: prosemirror-view@1.42.4: resolution: {integrity: sha512-H/LErnE8Vms1GYkvhfj6G3K9rc2p+o5EHGmTwvPOl0f21wPPxlMVRB8ICOseH+COb2oPKFEoufbgY6yet/dR4w==} + protocol-buffers-schema@3.6.1: + resolution: {integrity: sha512-VG2K63Igkiv9p76tk1lilczEK1cT+kCjKtkdhw1dQZV3k3IXJbd3o6Ho8b9zJZaHSnT2hKe4I+ObmX9w6m5SmQ==} + proxy-from-env@1.1.0: resolution: {integrity: sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==} @@ -3118,6 +3196,9 @@ packages: query-selector-shadow-dom@1.0.1: resolution: {integrity: sha512-lT5yCqEBgfoMYpf3F2xQRK7zEr1rhIIZuceDK6+xRkJQ4NMbHTwXqk4NkwDwQMNqXgG9r9fyHnzwNVs6zV5KRw==} + quickselect@3.0.0: + resolution: {integrity: sha512-XdjUArbK4Bm5fLLvlm5KpTFOiOThgfWWI4axAZDWg4E/0mKdZyI9tNEfds27qCi1ze/vwTR16kvmmGhRra3c2g==} + react-dom@19.3.0: resolution: {integrity: sha512-JDk8dgif51OjFoDE70+OT9ICyYr+69HlmihNwp1+Nsfbna3t5sIiCa9ZJktDmQ4/1b/rn26hIAR2uYXDMr5r0Q==} peerDependencies: @@ -3205,6 +3286,9 @@ packages: resolution: {integrity: sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==} engines: {node: '>=4'} + resolve-protobuf-schema@2.1.0: + resolution: {integrity: sha512-kI5ffTiZWmJaS/huM8wZfEMer1eRd7oJQhDuxeCLe3t7N7mX3z94CN0xPxBQxFYQTSNz9T0i+v6inKqSdK8xrQ==} + rollup@4.65.0: resolution: {integrity: sha512-QVCvQUTGDN6JRwi3jVGCY3H4aTHvi9rX0LyoBMkGUvdh/Z6O51CzcLz85BWZaTCDGhl6ySGqYZs+xI1jmPqGcw==} engines: {node: '>=18.0.0', npm: '>=8.0.0'} @@ -3338,6 +3422,9 @@ packages: resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} engines: {node: '>=12.0.0'} + tinyqueue@3.0.0: + resolution: {integrity: sha512-gRa9gwYU3ECmQYv3lslts5hxuIa90veaEcxDYuu3QGOIAEM2mOZkVHp48ANJuu1CURtRdHKUBY5Lm1tHV+sD4g==} + tinyrainbow@3.1.1: resolution: {integrity: sha512-yau8yJdTt989Mm0Bd/236QnzEiPf2xLLTqUZRUJOo/3CB078LSwzei343DgtJVmfJKJE3TMINY1u42SQsP6mXw==} engines: {node: '>=14.0.0'} @@ -4012,6 +4099,47 @@ snapshots: '@solid-primitives/utils': 6.4.1(solid-js@1.9.15) solid-js: 1.9.15 + '@mapbox/jsonlint-lines-primitives@2.0.3': {} + + '@mapbox/point-geometry@1.1.0': {} + + '@mapbox/tiny-sdf@2.3.0': {} + + '@mapbox/unitbezier@0.0.1': {} + + '@mapbox/unitbezier@1.0.0': {} + + '@mapbox/vector-tile@2.0.5': + dependencies: + '@mapbox/point-geometry': 1.1.0 + '@types/geojson': 7946.0.16 + pbf: 4.0.2 + + '@mapbox/whoots-js@3.1.0': {} + + '@maplibre/geojson-vt@6.3.0': + dependencies: + kdbush: 4.1.0 + + '@maplibre/maplibre-gl-style-spec@24.10.0': + dependencies: + '@mapbox/jsonlint-lines-primitives': 2.0.3 + '@mapbox/unitbezier': 1.0.0 + json-stringify-pretty-compact: 4.0.0 + minimist: 1.2.8 + quickselect: 3.0.0 + tinyqueue: 3.0.0 + + '@maplibre/mlt@1.3.0': + dependencies: + '@mapbox/point-geometry': 1.1.0 + + '@maplibre/vt-pbf@4.3.3': + dependencies: + '@mapbox/point-geometry': 1.1.0 + '@types/geojson': 7946.0.16 + pbf: 5.1.2 + '@napi-rs/lzma-linux-x64-gnu@1.5.1': optional: true @@ -5174,6 +5302,8 @@ snapshots: '@types/estree@1.0.9': {} + '@types/geojson@7946.0.16': {} + '@types/json-schema@7.0.15': {} '@types/node@24.13.5': @@ -5568,6 +5698,8 @@ snapshots: es-errors: 1.3.0 gopd: 1.2.0 + earcut@3.2.4: {} + electron-to-chromium@1.5.431: {} enhanced-resolve@5.25.1: @@ -5791,6 +5923,8 @@ snapshots: dunder-proto: 1.0.1 es-object-atoms: 1.1.2 + gl-matrix@3.4.4: {} + glob-parent@6.0.2: dependencies: is-glob: 4.0.3 @@ -5947,8 +6081,12 @@ snapshots: json-stable-stringify-without-jsonify@1.0.1: {} + json-stringify-pretty-compact@4.0.0: {} + json5@2.2.3: {} + kdbush@4.1.0: {} + keyv@4.5.4: dependencies: json-buffer: 3.0.1 @@ -6041,6 +6179,28 @@ snapshots: dependencies: semver: 7.8.5 + maplibre-gl@5.24.0: + dependencies: + '@mapbox/jsonlint-lines-primitives': 2.0.3 + '@mapbox/point-geometry': 1.1.0 + '@mapbox/tiny-sdf': 2.3.0 + '@mapbox/unitbezier': 0.0.1 + '@mapbox/vector-tile': 2.0.5 + '@mapbox/whoots-js': 3.1.0 + '@maplibre/geojson-vt': 6.3.0 + '@maplibre/maplibre-gl-style-spec': 24.10.0 + '@maplibre/mlt': 1.3.0 + '@maplibre/vt-pbf': 4.3.3 + '@types/geojson': 7946.0.16 + earcut: 3.2.4 + gl-matrix: 3.4.4 + kdbush: 4.1.0 + murmurhash-js: 1.0.0 + pbf: 4.0.2 + potpack: 2.1.0 + quickselect: 3.0.0 + tinyqueue: 3.0.0 + math-intrinsics@1.1.0: {} mdn-data@2.27.1: {} @@ -6061,6 +6221,8 @@ snapshots: dependencies: brace-expansion: 1.1.21 + minimist@1.2.8: {} + minipass@7.1.3: {} motion-dom@12.43.0: @@ -6079,6 +6241,8 @@ snapshots: ms@2.1.3: {} + murmurhash-js@1.0.0: {} + nanoid@3.3.20: {} natural-compare@1.4.0: {} @@ -6136,6 +6300,14 @@ snapshots: pathe@2.0.3: {} + pbf@4.0.2: + dependencies: + resolve-protobuf-schema: 2.1.0 + + pbf@5.1.2: + dependencies: + resolve-protobuf-schema: 2.1.0 + picocolors@1.1.1: {} picomatch@4.0.7: {} @@ -6164,6 +6336,8 @@ snapshots: transitivePeerDependencies: - preact-render-to-string + potpack@2.1.0: {} + preact@10.29.8: {} prelude-ls@1.2.1: {} @@ -6250,6 +6424,8 @@ snapshots: prosemirror-state: 1.4.4 prosemirror-transform: 1.12.1 + protocol-buffers-schema@3.6.1: {} + proxy-from-env@1.1.0: {} proxy-from-env@2.1.0: {} @@ -6262,6 +6438,8 @@ snapshots: query-selector-shadow-dom@1.0.1: {} + quickselect@3.0.0: {} + react-dom@19.3.0(react@19.3.0): dependencies: react: 19.3.0 @@ -6330,6 +6508,10 @@ snapshots: resolve-from@4.0.0: {} + resolve-protobuf-schema@2.1.0: + dependencies: + protocol-buffers-schema: 3.6.1 + rollup@4.65.0: dependencies: '@types/estree': 1.0.9 @@ -6460,6 +6642,8 @@ snapshots: fdir: 6.5.0(picomatch@4.0.7) picomatch: 4.0.7 + tinyqueue@3.0.0: {} + tinyrainbow@3.1.1: {} tldts-core@7.4.13: {} diff --git a/web/securityHeaders.ts b/web/securityHeaders.ts index f3a97984a..f5272d611 100644 --- a/web/securityHeaders.ts +++ b/web/securityHeaders.ts @@ -1,5 +1,8 @@ export const mailPreviewCsp = "default-src 'none'; script-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'self'; style-src 'unsafe-inline'; img-src data: https: http:; font-src data: https:; media-src https:"; +// The lead finder map's default tiles, styles, sprites and glyphs all come from here. +export const mapTileOrigin = "https://tiles.openfreemap.org"; + export function dashboardCsp({ scripts = [], styles = [], nonce = "", connections = [], analytics = [], images = [] }: { scripts?: string[]; styles?: string[]; @@ -15,7 +18,7 @@ export function dashboardCsp({ scripts = [], styles = [], nonce = "", connection "script-src-attr 'none'", `style-src 'self' ${[...authorization, ...styles].join(" ")}`, "style-src-attr 'unsafe-inline'", - `connect-src 'self' ${[...connections, ...analytics].join(" ")}`, + `connect-src 'self' ${mapTileOrigin} ${[...connections, ...analytics].join(" ")}`, `img-src 'self' data: blob: ${images.join(" ")}`, "font-src 'self'", "frame-src 'self' https://challenges.cloudflare.com", diff --git a/web/src/app/app/integrations/_components/ConnectDialog.tsx b/web/src/app/app/integrations/_components/ConnectDialog.tsx index 20aaf9161..c07b2a817 100644 --- a/web/src/app/app/integrations/_components/ConnectDialog.tsx +++ b/web/src/app/app/integrations/_components/ConnectDialog.tsx @@ -51,6 +51,33 @@ const FIELDS_BY_PROVIDER: Record = { helper: "Settings → Integrations → API in Apollo. Use a master key, or one with access to lists, contact search and people enrichment. It is checked before it is saved.", }, ], + google_places: [ + { + key: "api_key", + label: "Google Maps Platform API key", + type: "password", + required: true, + helper: "Google Cloud console → APIs and services → Credentials. Enable Places API (New) for the key. One small search checks it before it is saved.", + }, + ], + foursquare: [ + { + key: "api_key", + label: "Foursquare service key", + type: "password", + required: true, + helper: "Foursquare developer console → your project → Service API keys. One small search checks it before it is saved.", + }, + ], + outscraper: [ + { + key: "api_key", + label: "Outscraper API key", + type: "password", + required: true, + helper: "Outscraper → Profile → API token. Searches and the email lookup are billed to your Outscraper balance.", + }, + ], cleanmylist: [ { key: "api_key", @@ -98,6 +125,9 @@ const NEXT_STEP: Record = { pipedrive: "Finish the CRM setup: what syncs, and in which direction.", salesforce: "Finish the setup: sync rules, field mapping and the first import.", apollo: "Import your first Apollo list, or enrich contacts you already have.", + google_places: "Open the Lead finder and pick Google Places as the source.", + foursquare: "Open the Lead finder and pick Foursquare as the source.", + outscraper: "Open the Lead finder and pick Outscraper as the source.", discord: "Choose which Warmbly events post to the channel.", }; diff --git a/web/src/app/app/integrations/_components/ProviderGlyph.tsx b/web/src/app/app/integrations/_components/ProviderGlyph.tsx index d4dd8f282..8dc108edb 100644 --- a/web/src/app/app/integrations/_components/ProviderGlyph.tsx +++ b/web/src/app/app/integrations/_components/ProviderGlyph.tsx @@ -9,6 +9,18 @@ import { RAW_BRAND_LOGOS } from "./brandLogos"; import { GLYPH_DIMS, type GlyphSize } from "./glyphSize"; const BRAND_ICON: Record = { + google_places: { + hex: "#4285F4", + path: "M19.527 4.799c1.212 2.608.937 5.678-.405 8.173-1.101 2.047-2.744 3.74-4.098 5.614-.619.858-1.244 1.75-1.669 2.727-.141.325-.263.658-.383.992-.121.333-.224.673-.34 1.008-.109.314-.236.684-.627.687h-.007c-.466-.001-.579-.53-.695-.887-.284-.874-.581-1.713-1.019-2.525-.51-.944-1.145-1.817-1.79-2.671L19.527 4.799zM8.545 7.705l-3.959 4.707c.724 1.54 1.821 2.863 2.871 4.18.247.31.494.622.737.936l4.984-5.925-.029.01c-1.741.601-3.691-.291-4.392-1.987a3.377 3.377 0 0 1-.209-.716c-.063-.437-.077-.761-.004-1.198l.001-.007zM5.492 3.149l-.003.004c-1.947 2.466-2.281 5.88-1.117 8.77l4.785-5.689-.058-.05-3.607-3.035zM14.661.436l-3.838 4.563a.295.295 0 0 1 .027-.01c1.6-.551 3.403.15 4.22 1.626.176.319.323.683.377 1.045.068.446.085.773.012 1.22l-.003.016 3.836-4.561A8.382 8.382 0 0 0 14.67.439l-.009-.003zM9.466 5.868L14.162.285l-.047-.012A8.31 8.31 0 0 0 11.986 0a8.439 8.439 0 0 0-6.169 2.766l-.016.018 3.665 3.084z", + }, + foursquare: { + hex: "#3333FF", + path: "M2.376 0h7.338v1.204h-6.12v3.372h5.44V5.78h-5.44v4.874H2.376V0zm-.208 20.16l1.19-.268c.213 1.473 1.232 2.352 2.89 2.352 1.487 0 2.664-.694 2.664-1.828 0-.807-.595-1.487-2.919-2.18-2.635-.752-3.513-1.715-3.513-3.13 0-1.829 1.473-2.805 3.613-2.805 2.393 0 3.456 1.218 3.825 2.89l-1.19.269c-.299-1.374-1.233-1.955-2.679-1.955-1.36 0-2.323.51-2.323 1.487 0 .793.624 1.403 2.777 2.083 2.565.793 3.67 1.658 3.67 3.301 0 2.04-1.715 3.103-3.896 3.103-2.281-.003-3.84-1.193-4.11-3.318zm9.223-2.238c0-3.159 2.068-5.624 5.242-5.624 3.159 0 5.2 2.479 5.2 5.624 0 1.573-.525 2.933-1.404 3.925a36.155 36.155 0 011.247 1.303l-.879.85a57.16 57.16 0 00-1.303-1.346c-.807.524-1.771.822-2.861.822-3.061 0-5.242-2.352-5.242-5.554zm7.181 3.825a31.241 31.241 0 00-1.247-1.148l.85-.863a36.537 36.537 0 011.331 1.218c.638-.764 1.02-1.813 1.02-3.046 0-2.493-1.516-4.39-3.896-4.39s-3.91 1.897-3.91 4.39c0 2.565 1.658 4.363 3.91 4.363.725 0 1.375-.184 1.942-.524z", + }, + openstreetmap: { + hex: "#7EBC6F", + path: "M2.672 23.969c-.352-.089-.534-.234-1.471-1.168C.085 21.688.014 21.579.018 20.999c0-.645-.196-.414 3.368-3.986 3.6-3.608 3.415-3.451 4.064-3.449.302 0 .378.016.62.14l.277.14 1.744-1.744-.218-.343c-.425-.662-.825-1.629-1.006-2.429a7.657 7.657 0 0 1 1.479-6.44c2.49-3.12 6.959-3.812 10.26-1.588 1.812 1.218 2.99 3.099 3.328 5.314.07.467.07 1.579 0 2.074a7.554 7.554 0 0 1-2.205 4.402 6.712 6.712 0 0 1-1.943 1.401c-.959.483-1.775.71-2.881.803-1.573.131-3.32-.305-4.656-1.163l-.343-.218-1.744 1.744.14.28c.125.241.14.316.14.617.003.651.156.467-3.426 4.049-2.761 2.756-3.186 3.164-3.398 3.261-.271.125-.69.171-.945.106zM17.485 13.95a6.425 6.425 0 0 0 4.603-3.51c1.391-2.899.455-6.306-2.227-8.108-.638-.43-1.529-.794-2.367-.962-.581-.117-1.809-.104-2.414.025a6.593 6.593 0 0 0-2.452 1.064c-.444.315-1.177 1.048-1.487 1.487a6.384 6.384 0 0 0 .38 7.907 6.406 6.406 0 0 0 3.901 2.136c.509.078 1.542.058 2.065-.037zm-3.738 7.376a80.97 80.97 0 0 1-2.196-.651c-.025-.028 1.207-4.396 1.257-4.449.023-.026 4.242 1.152 4.414 1.236.062.026-.003.288-.525 2.102a398.513 398.513 0 0 0-.635 2.236c-.025.087-.069.156-.097.156-.028-.003-1.028-.287-2.219-.631zm2.912.524c0-.053 1.227-4.333 1.246-4.347.047-.034 4.324-1.23 4.341-1.211.019.019-1.199 4.337-1.23 4.36-.02.019-4.126 1.191-4.259 1.218-.054.011-.098 0-.098-.019zm-7.105-1.911c.846-.852 1.599-1.627 1.674-1.728.171-.218.405-.732.472-1.015.026-.118.053-.352.058-.522l.011-.307.182-.051c.103-.028.193-.044.202-.034.023.025-1.207 4.321-1.246 4.36-.02.016-.677.213-1.464.436l-1.425.405 1.537-1.542zm8.289-3.06a1.371 1.371 0 0 1-.059-.187l-.044-.156.156-.028c1.339-.227 2.776-.856 3.908-1.713.16-.125.252-.171.265-.134.054.165.272.95.265.959-.034.034-4.48 1.282-4.492 1.261zm-15.083-1.3c-.05-.039-1.179-3.866-1.264-4.29-.016-.084.146-.044 2.174.536 2.121.604 2.192.629 2.222.74.028.098.011.129-.125.223-.084.059-.769.724-1.523 1.479a63.877 63.877 0 0 1-1.39 1.367c-.016 0-.056-.025-.093-.054zm.821-4.378c-1.188-.343-2.164-.623-2.167-.626-.016-.012 1.261-4.433 1.285-4.46.022-.022 4.422 1.211 4.469 1.252.009.009-.269 1.017-.618 2.239-.576 2.02-.643 2.224-.723 2.22-.05-.003-1.059-.285-2.247-.626zm2.959.538c.012-.031.212-.723.444-1.534l.42-1.476.056.321c.093.556.265 1.188.464 1.741.106.296.187.539.181.545-.008.006-.332.101-.719.212-.389.109-.741.21-.786.224-.058.016-.075.006-.059-.034zM4.905 6.112c-1.187-.339-2.167-.635-2.18-.654-.04-.062-1.246-4.321-1.23-4.338.026-.025 4.31 1.204 4.351 1.246.047.051 1.28 4.379 1.246 4.376L4.91 6.113zm2.148-1.713l-.519-1.806-.078-.28 1.693-.483c.934-.265 1.724-.495 1.76-.508.034-.016-.083.14-.26.336A8.729 8.729 0 0 0 7.69 5.23a4.348 4.348 0 0 0-.132.561c0 .293-.115-.025-.505-1.39z", + }, millionverifier: { hex: "#1FB25A", path: "M12 2C6.477 2 2 6.477 2 12s4.477 10 10 10 10-4.477 10-10S17.523 2 12 2zm-1.2 14.4-4.2-4.2 1.7-1.7 2.5 2.5 6.1-6.1 1.7 1.7-7.8 7.8z", diff --git a/web/src/app/app/integrations/_components/brandLogos.ts b/web/src/app/app/integrations/_components/brandLogos.ts index 407f1c09c..36d0c6fe8 100644 --- a/web/src/app/app/integrations/_components/brandLogos.ts +++ b/web/src/app/app/integrations/_components/brandLogos.ts @@ -79,6 +79,12 @@ const CLAY: RawBrandLogo = { inner: '', }; +// Outscraper: its cube mark is published only as a raster, so this embeds its own icon (outscraper.com favicon, 96px). +const OUTSCRAPER: RawBrandLogo = { + viewBox: "0 0 96 96", + inner: '', +}; + export const RAW_BRAND_LOGOS: Record = { cleanmylist: { viewBox: "0 0 64 64", @@ -89,4 +95,5 @@ export const RAW_BRAND_LOGOS: Record = { pipedrive: PIPEDRIVE, apollo: APOLLO, clay: CLAY, + outscraper: OUTSCRAPER, }; diff --git a/web/src/app/app/integrations/_components/glyphSize.ts b/web/src/app/app/integrations/_components/glyphSize.ts index 1d49e68a5..77badbb34 100644 --- a/web/src/app/app/integrations/_components/glyphSize.ts +++ b/web/src/app/app/integrations/_components/glyphSize.ts @@ -1,9 +1,10 @@ // Logo tile sizes shared by built-in marks and community app logos. -export type GlyphSize = 7 | 9 | 10 | 12; +export type GlyphSize = 5 | 7 | 9 | 10 | 12; // Larger tiles round a little more so an app page header mark reads as an icon. export const GLYPH_DIMS: Record = { + 5: { tile: "w-5 h-5 rounded", icon: "w-3.5 h-3.5", text: "text-[10px]" }, 7: { tile: "w-7 h-7 rounded-md", icon: "w-4 h-4", text: "text-[12px]" }, 9: { tile: "w-9 h-9 rounded-md", icon: "w-5 h-5", text: "text-[13px]" }, 10: { tile: "w-10 h-10 rounded-lg", icon: "w-6 h-6", text: "text-[15px]" }, diff --git a/web/src/app/app/leads/page.tsx b/web/src/app/app/leads/page.tsx new file mode 100644 index 000000000..56a0abaf2 --- /dev/null +++ b/web/src/app/app/leads/page.tsx @@ -0,0 +1,786 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import toast from "react-hot-toast/headless"; +import { motion } from "framer-motion"; +import { + CheckIcon, + FocusIcon, + HandIcon, + LassoIcon, + LayersIcon, + ListIcon, + Loader2Icon, + MapIcon, + MapPinnedIcon, + MinusIcon, + PanelLeftIcon, + PentagonIcon, + PlusIcon, + RotateCw, + SquareIcon, + CircleIcon, + XIcon, + Columns2Icon, + BoxIcon, +} from "lucide-react"; +import { PopoverMenu, PopoverMenuContent, PopoverMenuItem, PopoverMenuLabel, PopoverMenuSeparator, PopoverMenuTrigger } from "@/components/ui/popover-menu"; +import AddToContactsDialog from "@/components/app/leads/AddToContactsDialog"; +import EnrichmentProgress from "@/components/app/leads/EnrichmentProgress"; +import ExportDialog from "@/components/app/leads/ExportDialog"; +import LeadFilterBar from "@/components/app/leads/LeadFilterBar"; +import { EMPTY_REFINE, refineFilter, type Refine } from "@/components/app/leads/refine"; +import { LEGEND } from "@/components/app/leads/legend"; +import LeadDrawer from "@/components/app/leads/LeadDrawer"; +import LeadMap, { type ColorBy, type FlyTarget, type MapControls, type MapLayerMode, type MapTool, type MapView } from "@/components/app/leads/LeadMap"; +import LeadSelectionBar from "@/components/app/leads/LeadSelectionBar"; +import LeadsTable from "@/components/app/leads/LeadsTable"; +import SavedSearches from "@/components/app/leads/SavedSearches"; +import SearchPanel from "@/components/app/leads/SearchPanel"; +import { areaKm2, boundsOf, inPolygon } from "@/components/app/leads/geo"; +import { useConfirm } from "@/hooks/context/confirm"; +import type { AppError } from "@/lib/api/client/normalizeError"; +import { + useDeleteLeads, + useEnrichLeads, + useLeadEnrichments, + runActive, + useLeadFacets, + useLeadFinderConfig, + useLeadPoints, + useLeadSearches, + useLeadsList, + useSearchLeads, + useUpdateLeads, +} from "@/lib/api/hooks/app/leads/useLeads"; +import type { GeocodeResult, LatLng, LeadArea, LeadBounds, LeadFinderConfig, LeadProvider, LeadSearch, LeadSelection, LeadSort, LeadStatus } from "@/lib/api/models/app/leads/Lead"; +import buildError from "@/lib/helper/buildError"; +import { cn } from "@/lib/utils"; +import { useAppStore } from "@/stores"; + +type ViewMode = "split" | "map" | "list"; +type StyleChoice = "auto" | "light" | "dark" | "streets"; + +interface Prefs { + mode: ViewMode; + colorBy: ColorBy; + layer: MapLayerMode; + style: StyleChoice; + tilt: boolean; + view: { center: LatLng; zoom: number }; + // The source last picked in the dropdown; a saved search opening its own does not change it. + provider?: LeadProvider; +} + +const PREFS_KEY = "wb.leadFinder.prefs"; +const DEFAULT_PREFS: Prefs = { + mode: "split", + colorBy: "reach", + layer: "pins", + style: "auto", + tilt: false, + view: { center: { lat: 39.5, lng: -98.35 }, zoom: 3.4 }, +}; +const OSM_MAX_KM2 = 2500; + +// The bounds a map the size of v shows around center at zoom. +function boundsAt(v: MapView, center: LatLng, zoom: number): LeadBounds { + const k = 2 ** (v.zoom - zoom); + const cos = (lat: number) => Math.cos((lat * Math.PI) / 180); + const halfLng = ((v.bounds.east - v.bounds.west) / 2) * k; + const halfLat = ((v.bounds.north - v.bounds.south) / 2) * k * (cos(center.lat) / cos(v.center.lat)); + return { south: center.lat - halfLat, north: center.lat + halfLat, west: center.lng - halfLng, east: center.lng + halfLng }; +} + +function loadPrefs(): Prefs { + try { + const raw = localStorage.getItem(PREFS_KEY); + return raw ? { ...DEFAULT_PREFS, ...(JSON.parse(raw) as Partial) } : DEFAULT_PREFS; + } catch { + return DEFAULT_PREFS; + } +} + +export default function LeadFinderPage() { + const config = useLeadFinderConfig(); + if (!config.data) { + return ( +
+ {config.isError ? ( +

{buildError(config.error as unknown as AppError)}

+ ) : ( + + )} +
+ ); + } + return ; +} + +function Finder({ config }: { config: LeadFinderConfig }) { + const resolvedTheme = useAppStore((s) => s.resolvedTheme); + const confirm = useConfirm(); + const [prefs, setPrefs] = useState(loadPrefs); + const patchPrefs = useCallback((p: Partial) => setPrefs((cur) => ({ ...cur, ...p })), []); + useEffect(() => { + const t = window.setTimeout(() => localStorage.setItem(PREFS_KEY, JSON.stringify(prefs)), 400); + return () => window.clearTimeout(t); + }, [prefs]); + + // Search form. + const [query, setQuery] = useState(""); + const [category, setCategory] = useState(""); + const [location, setLocation] = useState(""); + const [provider, setProvider] = useState(() => + prefs.provider && config.providers.some((p) => p.id === prefs.provider && p.available) ? prefs.provider : config.default_provider, + ); + const pickProvider = (p: LeadProvider) => { + setProvider(p); + patchPrefs({ provider: p }); + }; + const [area, setArea] = useState(null); + // The last search's outline; drawn on the map, never searched again on its own. + const [searched, setSearched] = useState(null); + const [tool, setTool] = useState("pan"); + const [view, setView] = useState(null); + const [fly, setFly] = useState(null); + const flyTo = (t: Omit) => setFly({ ...t, key: Date.now() }); + const controls = useRef(null); + + // What the list and the map show. + const [searchId, setSearchId] = useState(null); + const [refine, setRefine] = useState(EMPTY_REFINE); + const [text, setText] = useState(""); + const [sort, setSort] = useState("score"); + const [sideOpen, setSideOpen] = useState(false); + + // Selection and detail. + const [selected, setSelected] = useState>(new Set()); + const [allMatching, setAllMatching] = useState(false); + const [activeId, setActiveId] = useState(null); + const [hoverId, setHoverId] = useState(null); + const [dialog, setDialog] = useState<{ kind: "contacts" | "export"; selection: LeadSelection; count: number } | null>(null); + const lastClicked = useRef(null); + + const searches = useLeadSearches(); + const currentSearch = searches.data?.find((s) => s.id === searchId) ?? null; + + const viewBounds = view?.bounds; + const roundedBounds = useMemo(() => { + if (!refine.inView || !viewBounds) return undefined; + // Rounded outward, so a deep zoom never collapses the box to zero width. + const down = (n: number) => Math.floor(n * 1000) / 1000; + const up = (n: number) => Math.ceil(n * 1000) / 1000; + return { south: down(viewBounds.south), west: down(viewBounds.west), north: up(viewBounds.north), east: up(viewBounds.east) }; + }, [refine.inView, viewBounds]); + + const filter = useMemo(() => { + const f = refineFilter(refine); + if (searchId) f.search_id = searchId; + if (text.trim()) f.q = text.trim(); + if (roundedBounds) f.bounds = roundedBounds; + return f; + }, [refine, searchId, text, roundedBounds]); + + const runs = useLeadEnrichments(); + const runList = useMemo(() => runs.data ?? [], [runs.data]); + const list = useLeadsList(filter, sort, runList.some(runActive)); + const points = useLeadPoints(filter); + const facets = useLeadFacets(searchId ? { search_id: searchId } : {}); + const leads = useMemo(() => list.data?.pages.flatMap((p) => p.data) ?? [], [list.data]); + const total = list.data?.pages[0]?.pagination.total ?? 0; + + // A new filter starts a new selection. + useEffect(() => { + setSelected(new Set()); + setAllMatching(false); + }, [filter]); + + const search = useSearchLeads(); + const enrich = useEnrichLeads(); + const updateMany = useUpdateLeads(); + const remove = useDeleteLeads(); + + const providerInfo = config.providers.find((p) => p.id === provider); + const lookingFor = query.trim() || config.categories.find((c) => c.id === category)?.label || "businesses"; + const searchingLabel = search.isPending ? `Searching ${providerInfo?.name ?? "the map"} for ${lookingFor.toLowerCase()}…` : null; + const shownArea = area ?? searched; + const searchArea: LeadArea | null = area ?? (view ? { kind: "bbox", bounds: view.bounds } : null); + const blockedReason = !query.trim() && !category + ? "Pick a category or type what to look for." + : !providerInfo?.available + ? `Connect ${providerInfo?.name ?? "this source"} under Integrations to search with it.` + : searchArea && provider === "osm" && areaKm2(searchArea.bounds) > OSM_MAX_KM2 + ? "Zoom in or draw a smaller area. OpenStreetMap searches up to 2,500 km² at a time." + : !searchArea + ? "Move the map to where you want to search." + : null; + + const runSearch = async () => { + if (blockedReason || !searchArea || search.isPending) return; + try { + const res = await search.mutateAsync({ + provider, + query: query.trim(), + category, + location_label: location.trim(), + area: searchArea, + language: navigator.language.slice(0, 2), + }); + setSearchId(res.search.id); + setSearched(res.search.area); + setSideOpen(false); + if (res.leads.length) { + flyTo({ bounds: boundsOf(res.leads.map((l) => ({ lat: l.latitude, lng: l.longitude }))) }); + } + const credits = res.credits_charged ? ` · ${res.credits_charged} credit${res.credits_charged === 1 ? "" : "s"}` : ""; + if (res.found === 0) toast(`Nothing found in this area${res.outside_area ? `; ${res.outside_area} results fell just outside it` : ""}`); + else toast.success(`Found ${res.found.toLocaleString()} business${res.found === 1 ? "" : "es"}${credits}`); + } catch (e) { + toast.error(buildError(e as AppError)); + } + }; + + const loadMore = async () => { + if (!currentSearch) return; + try { + const res = await search.mutateAsync({ search_id: currentSearch.id, language: navigator.language.slice(0, 2) }); + toast.success(res.found ? `${res.found.toLocaleString()} more found` : "No more results in this area"); + } catch (e) { + toast.error(buildError(e as AppError)); + } + }; + + const openSearch = (s: LeadSearch) => { + setSearchId(s.id); + setArea(s.area); + setSearched(null); + setQuery(s.query); + setCategory(s.category); + setLocation(s.location_label); + if (config.providers.find((p) => p.id === s.provider)?.available) setProvider(s.provider); + flyTo({ bounds: s.area.bounds }); + setSideOpen(false); + }; + + const clearSearch = () => { + setSearchId(null); + setArea(null); + setSearched(null); + }; + + // Until the flight lands, a search covers where the map is going, not where it was. + const onPlace = (r: GeocodeResult) => { + setArea(null); + const bounds = r.bounds; + if (bounds) { + setView((v) => ({ center: r.center, zoom: v?.zoom ?? 14, bounds })); + flyTo({ bounds }); + } else { + setView((v) => v && { center: r.center, zoom: 14, bounds: boundsAt(v, r.center, 14) }); + flyTo({ center: r.center, zoom: 14 }); + } + }; + + // Selection. + const selection: LeadSelection = allMatching ? { all: true, filter } : { lead_ids: [...selected] }; + const selectedCount = allMatching ? Math.min(total, 5000) : selected.size; + const toggle = (id: string, range: boolean) => { + setAllMatching(false); + setSelected((cur) => { + const next = new Set(cur); + if (range && lastClicked.current) { + const a = leads.findIndex((l) => l.id === lastClicked.current); + const b = leads.findIndex((l) => l.id === id); + if (a >= 0 && b >= 0) { + for (const l of leads.slice(Math.min(a, b), Math.max(a, b) + 1)) next.add(l.id); + return next; + } + } + if (next.has(id)) next.delete(id); + else next.add(id); + return next; + }); + lastClicked.current = id; + }; + const clearSelection = () => { + setSelected(new Set()); + setAllMatching(false); + }; + const onLasso = (poly: LatLng[]) => { + const inside = (points.data?.data ?? []).filter((p) => inPolygon(poly, { lat: p.latitude, lng: p.longitude })).map((p) => p.id); + setAllMatching(false); + setSelected((cur) => new Set([...cur, ...inside])); + toast(inside.length ? `Selected ${inside.length} lead${inside.length === 1 ? "" : "s"} in the shape` : "No leads inside that shape"); + }; + + const startEnrich = async (sel: LeadSelection) => { + try { + const run = await enrich.mutateAsync({ ...sel, verify: true, people: true }); + toast.success(`Reading ${run.total.toLocaleString()} website${run.total === 1 ? "" : "s"} for people and contact details`); + } catch (e) { + toast.error(buildError(e as AppError)); + } + }; + const setStatus = async (status: LeadStatus) => { + try { + const res = await updateMany.mutateAsync({ ...selection, status }); + toast.success(`${res.updated.toLocaleString()} updated`); + clearSelection(); + } catch (e) { + toast.error(buildError(e as AppError)); + } + }; + const addTag = async (tag: string) => { + try { + await updateMany.mutateAsync({ ...selection, add_tags: [tag] }); + toast.success(`Tagged ${selectedCount.toLocaleString()} with ${tag}`); + } catch (e) { + toast.error(buildError(e as AppError)); + } + }; + const deleteSelected = () => + confirm?.show( + `Delete ${selectedCount.toLocaleString()} lead${selectedCount === 1 ? "" : "s"}? Contacts already made from them stay.`, + async () => { + try { + await remove.mutateAsync(selection); + clearSelection(); + setActiveId(null); + } catch (e) { + toast.error(buildError(e as AppError)); + } + }, + ); + + const pickPoint = (id: string, additive: boolean) => { + if (additive) return toggle(id, false); + setActiveId(id); + }; + + const styleUrl = useMemo(() => { + const dark = prefs.style === "dark" || (prefs.style === "auto" && resolvedTheme === "dark"); + if (prefs.style === "streets" && config.map.style_light.includes("tiles.openfreemap.org/styles/positron")) { + return config.map.style_light.replace("/positron", "/liberty"); + } + return dark ? config.map.style_dark : config.map.style_light; + }, [prefs.style, resolvedTheme, config.map]); + const darkMap = prefs.style === "dark" || (prefs.style === "auto" && resolvedTheme === "dark"); + const highlight = useMemo(() => { + const s = new Set(selected); + if (hoverId) s.add(hoverId); + return s; + }, [selected, hoverId]); + + const showMap = prefs.mode !== "list"; + const showList = prefs.mode !== "map"; + + // One column, no switching: the search form, then every past search under it. + const sidebar = ( +
+
+ Find businesses + +
+
+ + = 9 ? view.center : null} + provider={provider} + onProvider={pickProvider} + area={area} + onClearArea={() => { + setArea(null); + setSearched(null); + }} + onTool={(t) => { + setTool(t); + setSideOpen(false); + }} + searching={search.isPending} + onSearch={runSearch} + blockedReason={blockedReason} + /> + + + { + openSearch(s); + setSideOpen(false); + }} + onDelete={(id) => id === searchId && clearSearch()} + /> + +
+
+ ); + + return ( +
+
+ + +

Lead finder

+
+ {currentSearch ? ( + + {currentSearch.name} + + + ) : ( + All leads + )} + {currentSearch?.has_more && ( + + )} +
+ {( + [ + ["map", "Map", MapIcon], + ["split", "Split", Columns2Icon], + ["list", "List", ListIcon], + ] as const + ).map(([key, label, Icon]) => ( + + ))} +
+
+ +
+ + {sideOpen &&
{sidebar}
} + +
+ + {!showList && } + {showMap && ( +
+ setTool("pan")} + onArea={setArea} + onLasso={onLasso} + onPick={pickPoint} + onView={(v) => { + setView(v); + patchPrefs({ view: { center: v.center, zoom: v.zoom } }); + }} + /> + + controls.current?.zoomBy(d)} + onFit={() => { + const pts = points.data?.data ?? []; + if (pts.length) flyTo({ bounds: boundsOf(pts.map((p) => ({ lat: p.latitude, lng: p.longitude }))) }); + else if (shownArea) flyTo({ bounds: shownArea.bounds }); + }} + /> + {tool !== "pan" && setTool("pan")} />} + {tool === "pan" && !blockedReason && ( +
+ +
+ )} + + {points.isFetching && ( +
+ + Updating pins +
+ )} + {!searchId && (points.data?.data.length ?? 0) === 0 && !points.isPending && } +
+ )} + {showList && ( +
+ list.refetch()} + hasMore={!!list.hasNextPage} + loadingMore={list.isFetchingNextPage} + onMore={() => list.fetchNextPage()} + sort={sort} + onSort={setSort} + selected={selected} + allMatching={allMatching} + onToggle={toggle} + onTogglePage={(on) => { + setAllMatching(false); + setSelected(on ? new Set(leads.map((l) => l.id)) : new Set()); + }} + onSelectAllMatching={() => setAllMatching(true)} + activeId={activeId} + onOpen={(id) => { + setActiveId(id); + const l = leads.find((x) => x.id === id); + if (l && showMap) flyTo({ center: { lat: l.latitude, lng: l.longitude }, zoom: 15 }); + }} + onHover={setHoverId} + banner={} + /> +
+ )} + setActiveId(null)} + onAddToContacts={(id) => setDialog({ kind: "contacts", selection: { lead_ids: [id] }, count: 1 })} + /> +
+
+ + startEnrich(selection)} + onAddToContacts={() => setDialog({ kind: "contacts", selection, count: selectedCount })} + onExport={() => setDialog({ kind: "export", selection, count: selectedCount })} + onStatus={setStatus} + onTag={addTag} + onDelete={deleteSelected} + onClear={clearSelection} + /> + setDialog(null)} + selection={dialog?.selection ?? {}} + count={dialog?.count ?? 0} + suggestedSegment={currentSearch?.name} + /> + setDialog(null)} selection={dialog?.selection ?? {}} count={dialog?.count ?? 0} config={config} /> +
+ ); +} + +const TOOLS: { id: MapTool; label: string; icon: React.ReactNode }[] = [ + { id: "pan", label: "Move the map", icon: }, + { id: "rect", label: "Draw a rectangle to search", icon: }, + { id: "circle", label: "Draw a circle to search", icon: }, + { id: "polygon", label: "Draw a shape to search", icon: }, + { id: "lasso", label: "Lasso leads to select them", icon: }, +]; + +function MapToolbar({ tool, onTool }: { tool: MapTool; onTool: (t: MapTool) => void }) { + return ( +
+ {TOOLS.map((t) => ( + + ))} +
+ ); +} + +const HINTS: Record, string> = { + rect: "Drag to draw a rectangle", + circle: "Drag from the center outwards", + polygon: "Click to add corners; double-click or Enter to finish", + lasso: "Drag around the leads you want to select", +}; + +function ToolHint({ tool, onCancel }: { tool: Exclude; onCancel: () => void }) { + return ( +
+ {HINTS[tool]} + +
+ ); +} + +function MapControlsBar({ prefs, onPrefs, onZoom, onFit }: { prefs: Prefs; onPrefs: (p: Partial) => void; onZoom: (d: number) => void; onFit: () => void }) { + const btn = "size-7 rounded-md inline-flex items-center justify-center text-slate-600 hover:bg-slate-100 hover:text-slate-900"; + const check = (on: boolean) => (on ? : undefined); + return ( +
+
+ + + + + + Show leads as + onPrefs({ layer: "pins" })} trailing={check(prefs.layer === "pins")}> + Pins + + onPrefs({ layer: "heat" })} trailing={check(prefs.layer === "heat")}> + Heatmap + + + Color pins by + {( + [ + ["reach", "Reachability"], + ["status", "Status"], + ["score", "Score"], + ["rating", "Rating"], + ] as const + ).map(([id, label]) => ( + onPrefs({ colorBy: id })} trailing={check(prefs.colorBy === id)}> + {label} + + ))} + + Map style + {( + [ + ["auto", "Match the dashboard"], + ["light", "Light"], + ["dark", "Dark"], + ["streets", "Streets"], + ] as const + ).map(([id, label]) => ( + onPrefs({ style: id })} trailing={check(prefs.style === id)}> + {label} + + ))} + + + + +
+
+ + +
+
+ ); +} + +function Legend({ colorBy, layer, count, truncated }: { colorBy: ColorBy; layer: MapLayerMode; count: number; truncated: boolean }) { + return ( +
+ + {count.toLocaleString()} + {truncated ? "+" : ""} on map + + {layer === "pins" && + LEGEND[colorBy].map((l) => ( + + + {l.label} + + ))} + {layer === "heat" && Brighter where leads are denser and better} +
+ ); +} + +function EmptyHint() { + return ( +
+
+ +

Find businesses on the map

+

+ Pick a category, go to a city, then search the view or draw the exact area. Find people and emails reads each business's own website for who runs it and how to reach them. +

+
+
+ ); +} diff --git a/web/src/components/app/contacts/contact-edit/ActivityTab.tsx b/web/src/components/app/contacts/contact-edit/ActivityTab.tsx index 441a5c3e0..4ff452f60 100644 --- a/web/src/components/app/contacts/contact-edit/ActivityTab.tsx +++ b/web/src/components/app/contacts/contact-edit/ActivityTab.tsx @@ -1574,6 +1574,8 @@ export function sourceLabel(source?: string | null): string { return "Imported from Apollo"; case "clay": return "Sent from Clay"; + case "lead_finder": + return "Found with the lead finder"; case "unknown": case undefined: case null: @@ -1653,6 +1655,8 @@ function createdLabel(source?: string | null): string { return "Imported from Apollo"; case "clay": return "Sent from Clay"; + case "lead_finder": + return "Added from the lead finder"; case "manual": return "Created manually"; default: diff --git a/web/src/components/app/leads/AddToContactsDialog.tsx b/web/src/components/app/leads/AddToContactsDialog.tsx new file mode 100644 index 000000000..f39801235 --- /dev/null +++ b/web/src/components/app/leads/AddToContactsDialog.tsx @@ -0,0 +1,283 @@ +import { useRef, useState } from "react"; +import toast from "react-hot-toast/headless"; +import { Link } from "@tanstack/react-router"; +import { ArrowRightIcon, BuildingIcon, FolderTreeIcon, Loader2Icon, type LucideIcon, MegaphoneIcon, TagsIcon, UserPlusIcon, UsersIcon } from "lucide-react"; +import CategoryPicker from "@/components/app/contacts/CategoryPicker"; +import { CampaignMultiPicker, SegmentMultiPicker } from "@/components/app/segments/SegmentPickers"; +import { Toggle } from "@/components/app/campaigns/preferences/components/CampaignPreferenceBoolBox"; +import { Checkbox } from "@/components/ui/checkbox"; +import type { AppError } from "@/lib/api/client/normalizeError"; +import { useAddLeadsToContacts } from "@/lib/api/hooks/app/leads/useLeads"; +import type { AddLeadsToContactsResult, LeadContactsWho, LeadSelection } from "@/lib/api/models/app/leads/Lead"; +import buildError from "@/lib/helper/buildError"; +import { cn } from "@/lib/utils"; +import LeadDialog from "./LeadDialog"; + +const WHO: { id: LeadContactsWho; label: string; hint: string; icon: LucideIcon }[] = [ + { id: "business", label: "The business", hint: "Each business's own address", icon: BuildingIcon }, + { id: "people", label: "The people", hint: "Owners, managers and staff found there", icon: UsersIcon }, + { id: "both", label: "Both", hint: "People first, then the business", icon: UserPlusIcon }, +]; + +export default function AddToContactsDialog({ + open, + onClose, + selection, + count, + suggestedSegment, +}: { + open: boolean; + onClose: () => void; + selection: LeadSelection; + count: number; + // Offered as the name of a new segment, usually the search's own name. + suggestedSegment?: string; +}) { + const add = useAddLeadsToContacts(); + const [who, setWho] = useState("business"); + const [segmentIds, setSegmentIds] = useState([]); + const [categoryIds, setCategoryIds] = useState([]); + const [campaignIds, setCampaignIds] = useState([]); + const [skipActive, setSkipActive] = useState(true); + const [verifiedOnly, setVerifiedOnly] = useState(false); + const [includeGuessed, setIncludeGuessed] = useState(false); + const [keepExisting, setKeepExisting] = useState(false); + const [result, setResult] = useState(null); + + // Bumped on close, so an import that finishes after it does not show its result. + const attempt = useRef(0); + const close = () => { + attempt.current++; + setResult(null); + onClose(); + }; + + const submit = async () => { + const mine = ++attempt.current; + try { + const res = await add.mutateAsync({ + ...selection, + who, + segment_ids: segmentIds, + category_ids: categoryIds, + campaign_ids: campaignIds, + skip_active_in_other_campaigns: campaignIds.length > 0 && skipActive, + verified_only: verifiedOnly, + include_guessed: includeGuessed, + keep_existing: keepExisting, + }); + if (mine === attempt.current) setResult(res); + const n = res.imported + res.updated; + if (n > 0) toast.success(`${n.toLocaleString()} contact${n === 1 ? "" : "s"} added`); + } catch (e) { + toast.error(buildError(e as AppError)); + } + }; + + return ( + } + eyebrow="Add to contacts" + title={`${count.toLocaleString()} lead${count === 1 ? "" : "s"}`} + footer={ + result ? ( + <> + + Open contacts + + + + + ) : ( + <> + + + + ) + } + > + {result ? ( + + ) : ( +
+
+ Who to add +
+ {WHO.map((w) => { + const on = who === w.id; + return ( + + ); + })} +
+

+ {who === "business" + ? "The business name becomes the company, with its website, address, rating and socials as fields." + : "Each person comes in with their name, title and LinkedIn, and the business as their company."}{" "} + Leads without an email stay in the finder. +

+
+ +
+
+

Add them to

+

Optional. Every contact made from this selection gets these.

+
+ + + + + + + + + {campaignIds.length > 0 && ( + + )} + +
+ +
+ + {who !== "business" && !verifiedOnly && ( + + )} + +
+
+ )} +
+ ); +} + +function Outcome({ result, who, keepExisting }: { result: AddLeadsToContactsResult; who: LeadContactsWho; keepExisting: boolean }) { + const added = result.imported + result.updated; + return ( +
+
+
+ +
+
+
+ {added.toLocaleString()} contact{added === 1 ? "" : "s"} added +
+
+ {result.imported.toLocaleString()} new, {result.updated.toLocaleString()} updated +
+
+
+
+ + + {who !== "business" && } + + + {result.failed > 0 && } +
+ {result.no_email > 0 && ( +

Anyone without an email stays in the finder. Run Find people and emails on them, then add them again.

+ )} +
+ ); +} + +function SectionLabel({ children }: { children: React.ReactNode }) { + return
{children}
; +} + +function Row({ icon: Icon, label, hint, children }: { icon: LucideIcon; label: string; hint: string; children: React.ReactNode }) { + return ( +
+
+ +
+

{label}

+

{hint}

+
+
+
{children}
+
+ ); +} + +function Option({ title, hint, children }: { title: string; hint: string; children: React.ReactNode }) { + return ( +
+
+
{title}
+
{hint}
+
+ {children} +
+ ); +} + +function Stat({ label, value, tone }: { label: string; value: number; tone?: string }) { + return ( +
+
{label}
+
{value.toLocaleString()}
+
+ ); +} diff --git a/web/src/components/app/leads/EnrichmentProgress.tsx b/web/src/components/app/leads/EnrichmentProgress.tsx new file mode 100644 index 000000000..cbd64883b --- /dev/null +++ b/web/src/components/app/leads/EnrichmentProgress.tsx @@ -0,0 +1,123 @@ +import { useEffect, useMemo, useRef, useState } from "react"; +import { AnimatePresence, motion } from "framer-motion"; +import { useQueryClient } from "@tanstack/react-query"; +import { CheckCircle2Icon, TriangleAlertIcon, XIcon } from "lucide-react"; +import { LEADS_KEY, runActive } from "@/lib/api/hooks/app/leads/useLeads"; +import type { LeadEnrichmentRun } from "@/lib/api/models/app/leads/Lead"; +import { cn } from "@/lib/utils"; + +// The strip on top of the leads list: a search in flight, the website runs +// going in the background, and how each one ended. +export default function EnrichmentProgress({ runs, searching }: { runs: LeadEnrichmentRun[]; searching: string | null }) { + const qc = useQueryClient(); + const seen = useRef(new Map()); + const [finished, setFinished] = useState([]); + + // A run finishing refreshes the leads it touched and stays on screen a moment. + useEffect(() => { + const ended: LeadEnrichmentRun[] = []; + for (const r of runs) { + const before = seen.current.get(r.id); + if (before && before !== r.status && !runActive(r)) ended.push(r); + seen.current.set(r.id, r.status); + } + if (!ended.length) return; + qc.invalidateQueries({ queryKey: LEADS_KEY }); + setFinished((cur) => [...ended, ...cur].slice(0, 2)); + }, [runs, qc]); + + useEffect(() => { + if (!finished.length) return; + const t = setTimeout(() => setFinished((cur) => cur.slice(0, -1)), 9_000); + return () => clearTimeout(t); + }, [finished]); + + const active = useMemo(() => runs.filter(runActive), [runs]); + const total = active.reduce((n, r) => n + r.total, 0); + const processed = active.reduce((n, r) => n + r.processed, 0); + const emails = active.reduce((n, r) => n + r.emails_found, 0); + const people = active.reduce((n, r) => n + r.people_found, 0); + const pct = total ? Math.round((processed / total) * 100) : 0; + + return ( + + {searching && ( + + + {searching} + + + + + )} + {active.length > 0 && ( + + + Finding people and emails + + {processed.toLocaleString()} of {total.toLocaleString()} businesses + {emails > 0 && ` · ${emails.toLocaleString()} with an email`} + {people > 0 && ` · ${people.toLocaleString()} ${people === 1 ? "person" : "people"}`} + + Keeps going if you leave + {pct}% + + + + + + )} + {finished.map((r) => { + const failed = r.status === "error"; + return ( + + {failed ? : } + {failed ? "Stopped early" : "Done"} + + {failed && r.last_error + ? r.last_error + : `${r.emails_found.toLocaleString()} with an email${r.people ? `, ${r.people_found.toLocaleString()} ${r.people_found === 1 ? "person" : "people"}` : ""} from ${r.total.toLocaleString()} business${r.total === 1 ? "" : "es"}`} + {r.credits_consumed > 0 && ` · ${r.credits_consumed} credit${r.credits_consumed === 1 ? "" : "s"}`} + + + + ); + })} + + ); +} + +function Strip({ children, tone = "sky" }: { children: React.ReactNode; tone?: "sky" | "emerald" | "amber" }) { + return ( + +
+ {children} +
+
+ ); +} + +function Track({ children }: { children: React.ReactNode }) { + return
{children}
; +} diff --git a/web/src/components/app/leads/ExportDialog.tsx b/web/src/components/app/leads/ExportDialog.tsx new file mode 100644 index 000000000..624a8bf8b --- /dev/null +++ b/web/src/components/app/leads/ExportDialog.tsx @@ -0,0 +1,154 @@ +import { useEffect, useState } from "react"; +import toast from "react-hot-toast/headless"; +import { DownloadIcon, Loader2Icon } from "lucide-react"; +import { Checkbox } from "@/components/ui/checkbox"; +import type { AppError } from "@/lib/api/client/normalizeError"; +import { downloadBlob } from "@/lib/api/client/app/contacts/exportContacts"; +import { exportLeads } from "@/lib/api/client/app/leads/leads"; +import type { LeadExportFormat, LeadExportRows, LeadFinderConfig, LeadSelection } from "@/lib/api/models/app/leads/Lead"; +import buildError from "@/lib/helper/buildError"; +import { cn } from "@/lib/utils"; +import LeadDialog from "./LeadDialog"; + +const FORMATS: { id: LeadExportFormat; label: string; hint: string }[] = [ + { id: "csv", label: "CSV", hint: "Any spreadsheet or CRM" }, + { id: "xlsx", label: "Excel", hint: "Frozen header, numbers as numbers" }, + { id: "json", label: "JSON", hint: "For scripts and tools" }, +]; + +const ROWS: { id: LeadExportRows; label: string; hint: string }[] = [ + { id: "leads", label: "One row per business", hint: "Its own address, with the people in one column" }, + { id: "people", label: "One row per person", hint: "Name, title and address, then the business" }, +]; + +export default function ExportDialog({ + open, + onClose, + selection, + count, + config, +}: { + open: boolean; + onClose: () => void; + selection: LeadSelection; + count: number; + config: LeadFinderConfig; +}) { + const [format, setFormat] = useState("csv"); + const [rows, setRows] = useState("leads"); + const [columns, setColumns] = useState(config.default_export_columns); + const [busy, setBusy] = useState(false); + useEffect(() => { + if (open) setColumns(config.default_export_columns); + }, [open, config.default_export_columns]); + + // The people column only exists in per-business rows. + const sent = rows === "people" ? columns.filter((k) => k !== "people") : columns; + const toggle = (k: string) => setColumns((c) => (c.includes(k) ? c.filter((x) => x !== k) : [...config.export_columns.map((x) => x.key).filter((x) => c.includes(x) || x === k)])); + + const run = async () => { + setBusy(true); + try { + const blob = await exportLeads({ ...selection, format, columns: sent, rows }); + downloadBlob(blob, `${rows === "people" ? "lead-people" : "leads"}-${new Date().toISOString().slice(0, 10)}.${format}`); + toast.success(`Exported ${count.toLocaleString()} lead${count === 1 ? "" : "s"}`); + onClose(); + } catch (e) { + toast.error(buildError(e as AppError)); + } finally { + setBusy(false); + } + }; + + return ( + } + eyebrow="Export" + title={`${count.toLocaleString()} lead${count === 1 ? "" : "s"}`} + width={560} + footer={ + <> + + {rows === "people" ? `${config.person_columns.length} person columns + ${sent.length}` : `${sent.length} columns`} + + + + + } + > +
+
+ {ROWS.map((r) => ( + + ))} +
+
+ {FORMATS.map((f) => ( + + ))} +
+
+
+ {rows === "people" ? "Business columns" : "Columns"} + + · + +
+
+ {config.export_columns.filter((c) => rows === "leads" || c.key !== "people").map((c) => ( + + ))} +
+ {rows === "people" && ( +

+ Each row starts with {config.person_columns.map((c) => c.label.toLowerCase()).slice(0, 4).join(", ")} and more. Businesses with nobody found are left out. +

+ )} +
+
+
+ ); +} diff --git a/web/src/components/app/leads/FilterPanel.tsx b/web/src/components/app/leads/FilterPanel.tsx new file mode 100644 index 000000000..3751ff828 --- /dev/null +++ b/web/src/components/app/leads/FilterPanel.tsx @@ -0,0 +1,167 @@ +import { RotateCcwIcon } from "lucide-react"; +import { NumberInput } from "@/components/ui/field"; +import { Toggle } from "@/components/app/campaigns/preferences/components/CampaignPreferenceBoolBox"; +import type { LeadFacets, LeadStatus } from "@/lib/api/models/app/leads/Lead"; +import { cn } from "@/lib/utils"; +import { EMPTY_REFINE, refineCount, type ReachFilter, type Refine } from "./refine"; + +const REACH: { id: ReachFilter; label: string }[] = [ + { id: "email", label: "Has email" }, + { id: "people", label: "Has people" }, + { id: "website", label: "Has website" }, + { id: "phone", label: "Has phone" }, + { id: "socials", label: "Has socials" }, + { id: "no_website", label: "No website" }, +]; + +const STATUSES: { id: LeadStatus; label: string }[] = [ + { id: "new", label: "New" }, + { id: "saved", label: "Saved" }, + { id: "contacted", label: "Contacted" }, + { id: "dismissed", label: "Dismissed" }, +]; + +const RATINGS: { v: number | null; label: string }[] = [ + { v: null, label: "Any" }, + { v: 3, label: "3+" }, + { v: 4, label: "4+" }, + { v: 4.5, label: "4.5+" }, +]; + +export default function FilterPanel({ value, onChange, facets }: { value: Refine; onChange: (r: Refine) => void; facets?: LeadFacets }) { + const set = (k: K, v: Refine[K]) => onChange({ ...value, [k]: v }); + const toggle = (list: T[], v: T) => (list.includes(v) ? list.filter((x) => x !== v) : [...list, v]); + const count = refineCount(value); + return ( +
+
+ Refine results + {count > 0 && ( + + )} +
+ + {REACH.map((r) => ( + { + let next = toggle(value.reach, r.id); + if (r.id === "no_website") next = next.filter((x) => x !== "website"); + if (r.id === "website") next = next.filter((x) => x !== "no_website"); + set("reach", next); + }}> + {r.label} + + ))} + + +
+ {RATINGS.map((r) => ( + + ))} +
+
+
+ set("minReviews", v)} /> + set("maxReviews", v)} /> + set("minScore", Math.min(100, v))} /> +
+ + {STATUSES.map((s) => ( + set("statuses", toggle(value.statuses, s.id))}> + {s.label} + + ))} + + {facets && facets.categories.length > 1 && ( + + {facets.categories.slice(0, 12).map((c) => ( + set("category", value.category === c.value ? "" : c.value)}> + {c.value} + {c.count} + + ))} + + )} + {facets && facets.tags.length > 0 && ( + + {facets.tags.map((t) => ( + set("tag", value.tag === t.value ? "" : t.value)}> + {t.value} + {t.count} + + ))} + + )} +
+ set("inView", v)} /> + set("hideContacts", v)} /> + set("excludeChains", v)} /> + 0} + onChange={(v) => set("hideDismissed", v)} + /> +
+
+ ); +} + +function Group({ label, children }: { label: string; children: React.ReactNode }) { + return ( +
+
{label}
+
{children}
+
+ ); +} + +function Pill({ on, onClick, children }: { on: boolean; onClick: () => void; children: React.ReactNode }) { + return ( + + ); +} + +function NumField({ label, value, onChange }: { label: string; value: number; onChange: (v: number) => void }) { + return ( + + ); +} + +function Switch({ label, value, onChange, disabled }: { label: string; value: boolean; onChange: (v: boolean) => void; disabled?: boolean }) { + return ( +
+ {label} + +
+ ); +} diff --git a/web/src/components/app/leads/LeadDialog.tsx b/web/src/components/app/leads/LeadDialog.tsx new file mode 100644 index 000000000..cf7b33a9c --- /dev/null +++ b/web/src/components/app/leads/LeadDialog.tsx @@ -0,0 +1,82 @@ +import { AnimatePresence, motion } from "framer-motion"; +import { XIcon } from "lucide-react"; +import { useEffect } from "react"; + +// The card every lead finder dialog sits in; closes on backdrop and Escape. +export default function LeadDialog({ + open, + onClose, + icon, + eyebrow, + title, + children, + footer, + width = 520, +}: { + open: boolean; + onClose: () => void; + icon: React.ReactNode; + eyebrow: string; + title: string; + children: React.ReactNode; + footer: React.ReactNode; + width?: number; +}) { + useEffect(() => { + if (!open) return; + const key = (e: KeyboardEvent) => { + if (e.key !== "Escape") return; + if (document.querySelector("[data-floating]") || document.querySelector('[role="alertdialog"]')) return; + onClose(); + }; + window.addEventListener("keydown", key); + return () => window.removeEventListener("keydown", key); + }, [open, onClose]); + + return ( + + {open && ( + + e.stopPropagation()} + style={{ maxWidth: width }} + className="w-full rounded-lg bg-white border border-slate-200 shadow-[0_24px_48px_-12px_rgba(15,23,42,0.18),0_8px_16px_-8px_rgba(15,23,42,0.1)] overflow-hidden flex flex-col max-h-[85dvh]" + > +
+
{icon}
+ {eyebrow} +
+ {title} + +
+
{children}
+
{footer}
+
+
+ )} +
+ ); +} diff --git a/web/src/components/app/leads/LeadDrawer.tsx b/web/src/components/app/leads/LeadDrawer.tsx new file mode 100644 index 000000000..77975b25e --- /dev/null +++ b/web/src/components/app/leads/LeadDrawer.tsx @@ -0,0 +1,572 @@ +import { useEffect, useRef, useState } from "react"; +import { AnimatePresence, motion } from "framer-motion"; +import toast from "react-hot-toast/headless"; +import { + BuildingIcon, + CheckIcon, + ClockIcon, + CopyIcon, + ExternalLinkIcon, + FileTextIcon, + GlobeIcon, + InfoIcon, + Loader2Icon, + LockIcon, + MailIcon, + MapIcon, + MapPinIcon, + PhoneIcon, + SparklesIcon, + StarIcon, + TagIcon, + UserPlusIcon, + UsersIcon, + XIcon, +} from "lucide-react"; +import { Link } from "@tanstack/react-router"; +import ResourceViewers from "@/components/app/presence/ResourceViewers"; +import ScrollStrip from "@/components/ui/scroll-strip"; +import { usePresenceResource } from "@/hooks/PresenceProvider"; +import type { AppError } from "@/lib/api/client/normalizeError"; +import { useEnrichLeads, useLead, useUpdateLead } from "@/lib/api/hooks/app/leads/useLeads"; +import type { Lead, LeadFinderConfig, LeadStatus } from "@/lib/api/models/app/leads/Lead"; +import buildError from "@/lib/helper/buildError"; +import timeAgo from "@/lib/helper/timeAgo"; +import { cn } from "@/lib/utils"; +import PeopleTab from "./PeopleTab"; +import { ScoreBar } from "./badges"; +import { STATUS_LABEL, emailVerdict } from "./verdict"; + +type Tab = "overview" | "people" | "website" | "notes"; + +const SOCIAL_LABEL: Record = { + facebook: "Facebook", + instagram: "Instagram", + linkedin: "LinkedIn", + twitter: "X", + tiktok: "TikTok", + youtube: "YouTube", + pinterest: "Pinterest", + yelp: "Yelp", +}; + +export default function LeadDrawer({ + id, + config, + onClose, + onAddToContacts, +}: { + id: string | null; + config: LeadFinderConfig; + onClose: () => void; + onAddToContacts: (id: string) => void; +}) { + const lead = useLead(id); + const [tab, setTab] = useState("overview"); + usePresenceResource(id ? `lead:${id}` : null, "viewing"); + + useEffect(() => { + if (!id) return; + const key = (e: KeyboardEvent) => { + if (e.key !== "Escape" || document.querySelector("[data-floating]") || document.querySelector('[role="dialog"],[role="alertdialog"]')) return; + onClose(); + }; + window.addEventListener("keydown", key); + return () => window.removeEventListener("keydown", key); + }, [id, onClose]); + + return ( + + {id && ( + + {!lead.data ? ( +
+ {lead.isError ? ( +

This lead is no longer here.

+ ) : ( + + )} +
+ ) : ( + + )} +
+ )} +
+ ); +} + +function Body({ + lead, + config, + tab, + onTab, + onClose, + onAddToContacts, +}: { + lead: Lead; + config: LeadFinderConfig; + tab: Tab; + onTab: (t: Tab) => void; + onClose: () => void; + onAddToContacts: (id: string) => void; +}) { + const update = useUpdateLead(); + const enrich = useEnrichLeads(); + const provider = config.providers.find((p) => p.id === lead.provider)?.name ?? lead.provider; + const reachable = !!lead.email || (lead.people ?? []).some((p) => p.email && p.email_status !== "suppressed" && p.email_status !== "invalid"); + const setStatus = (status: LeadStatus) => + update.mutate({ id: lead.id, patch: { status } }, { onError: (e) => toast.error(buildError(e as unknown as AppError)) }); + + const findEmails = async () => { + try { + await enrich.mutateAsync({ lead_ids: [lead.id], verify: true, people: true }); + toast.success(lead.website ? `Reading ${lead.domain || "the website"} for people and contact details` : `Looking for ${lead.name}'s website`); + } catch (e) { + toast.error(buildError(e as AppError)); + } + }; + + return ( + <> +
+
+
+ +
+
+

{lead.name}

+

{[lead.category, lead.city].filter(Boolean).join(" · ") || provider}

+
+ + +
+
+
+ {(["new", "saved", "contacted", "dismissed"] as LeadStatus[]).map((s) => ( + + ))} +
+
+ +
+
+
+ + {lead.contact_id ? ( + + + In contacts + + ) : ( + + )} + {lead.website && ( + + + Site + + )} + {lead.maps_url && ( + + + Map + + )} +
+
+ + {( + [ + ["overview", "Overview", InfoIcon], + ["people", "People", UsersIcon], + ["website", "Website", GlobeIcon], + ["notes", "Notes", FileTextIcon], + ] as const + ).map(([key, label, Icon]) => ( + + ))} + +
+ {tab === "overview" && onTab("people")} />} + {tab === "people" && } + {tab === "website" && } + {tab === "notes" && } +
+ + ); +} + +function Section({ title, children }: { title: string; children: React.ReactNode }) { + return ( +
+

{title}

+ {children} +
+ ); +} + +function copy(v: string) { + navigator.clipboard?.writeText(v).then( + () => toast.success("Copied"), + () => toast.error("Could not copy"), + ); +} + +function Overview({ lead, provider, onPeople }: { lead: Lead; provider: string; onPeople: () => void }) { + const socials = Object.entries(lead.socials ?? {}); + const deciders = (lead.people ?? []).filter((p) => p.seniority !== "staff").slice(0, 3); + return ( + <> + {deciders.length > 0 && ( +
+ +
+ )} +
+ {lead.emails.length === 0 ? ( +

+ {lead.enrichment_status === "no_website" + ? "The listing has no website, and none could be confirmed from the business's name." + : lead.enrichment_status === "done" + ? "The website lists no email address." + : lead.enrichment_status === "failed" + ? `The website could not be read${lead.site.error ? `: ${lead.site.error}` : "."}` + : "Not looked for yet. Find people and emails reads the business's own site."} +

+ ) : ( +
    + {lead.emails.map((e) => { + const v = emailVerdict(e); + return ( +
  • + +
    +
    + {e.email} + {e.email === lead.email && Primary} +
    +
    + + {v.icon} + {v.label} + + · + {e.source === "website" ? "From the website" : `From ${provider}`} + {e.domain_match && · On their domain} +
    +
    + +
  • + ); + })} +
+ )} +
+
+
+ {lead.phone && ( + }> + + {lead.phone} + + + )} + {lead.website && ( + }> + + {lead.domain || lead.website} + + + {lead.site.found_website && Found from the name, confirmed on the site} + + )} + {lead.address && ( + }> + {lead.address} + + )} + {(lead.rating != null || lead.review_count != null) && ( + }> + + {lead.rating != null ? `${lead.rating.toFixed(1)} stars` : "No rating"} + {lead.review_count != null && from {lead.review_count.toLocaleString()} reviews} + {lead.price_level != null && · {"$".repeat(lead.price_level)}} + + + )} + {lead.business_status && lead.business_status !== "operational" && ( + }> + {lead.business_status === "closed" ? "Permanently closed" : "Temporarily closed"} + + )} + {lead.chain && ( + }> + Part of {lead.chain} + + )} +
+ {lead.description &&

{lead.description}

} +
+ {socials.length > 0 && ( +
+
+ {socials.map(([kind, url]) => ( + + {SOCIAL_LABEL[kind] ?? kind} + + + ))} +
+
+ )} + {lead.hours.length > 0 && ( +
+
    + {lead.hours.map((h) => ( +
  • + + {h} +
  • + ))} +
+
+ )} + {lead.categories.length > 0 && ( +
+
+ {lead.categories.map((c) => ( + + {c} + + ))} +
+
+ )} +

+ From {provider} · first found {timeAgo(lead.first_seen_at)} +

+ + ); +} + +function Fact({ icon, children }: { icon: React.ReactNode; children: React.ReactNode }) { + return ( +
+ {icon} +
{children}
+
+ ); +} + +function Website({ lead }: { lead: Lead }) { + const s = lead.site; + if (!lead.website) + return ( +

+ {lead.enrichment_status === "no_website" + ? "No website could be found for this business. That alone can be the reason to reach out." + : "The listing has no website. Find people and emails looks for one from the business's name first."} +

+ ); + if (!s.checked_at) return

Not read yet. Find people and emails reads the site and reports what it runs on.

; + if (!s.reachable) return

The website could not be read{s.error ? `: ${s.error}` : "."}

; + return ( + <> +
+
+ : }> + {s.https ? "Served over HTTPS" : "No HTTPS"} + + {s.platform && ( + }> + Built with {s.platform} + + )} + }> + + {s.pages ?? 1} page{(s.pages ?? 1) === 1 ? "" : "s"} read {timeAgo(s.checked_at)} + + +
+ {(s.title || s.description) && ( +
+ {s.title &&

{s.title}

} + {s.description &&

{s.description}

} +
+ )} +
+ {s.signals && s.signals.length > 0 && ( +
+
+ {s.signals.map((sig) => { + const gap = /^No |Not |Outdated/.test(sig); + return ( + + {sig} + + ); + })} +
+

Amber marks a gap you could offer to fix.

+
+ )} + + ); +} + +function Notes({ lead }: { lead: Lead }) { + const update = useUpdateLead(); + const [notes, setNotes] = useState(lead.notes); + // A teammate's save must not overwrite what is being typed here. + const dirty = useRef(false); + const [tag, setTag] = useState(""); + useEffect(() => { + if (!dirty.current) setNotes(lead.notes); + }, [lead.notes]); + const save = (patch: Parameters[0]["patch"]) => + update.mutate({ id: lead.id, patch }, { onError: (e) => toast.error(buildError(e as unknown as AppError)) }); + const addTag = () => { + const t = tag.trim(); + setTag(""); + if (!t || lead.tags.includes(t)) return; + save({ tags: [...lead.tags, t] }); + }; + return ( + <> +
+
+ {lead.tags.map((t) => ( + + + {t} + + + ))} + setTag(e.target.value)} + onKeyDown={(e) => { + if (e.key === "Enter" || e.key === ",") { + e.preventDefault(); + addTag(); + } + }} + onBlur={addTag} + placeholder="Add a tag…" + className="h-6 min-w-[100px] flex-1 rounded-md border border-transparent px-1.5 text-[12px] outline-none focus:border-slate-200" + /> +
+
+
+