Merge pull request #1156 from warmbly/feat/lead-finder-map-explorer

feat: add map-based lead finder with pluggable place sources, website email enrichment, export and add-to-contacts
This commit is contained in:
Matthew Meszaros
2026-11-07 08:36:24 +00:00
committed by GitHub
97 changed files with 15265 additions and 9 deletions
+15
View File
@@ -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
+26
View File
@@ -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,
+15
View File
@@ -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.
+9
View File
@@ -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:-}
+31
View File
@@ -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 |
+19
View File
@@ -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 |
@@ -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/).
@@ -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://<domain>/` and `https://<domain>/` 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.
+3
View File
@@ -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:
+159
View File
@@ -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
<Steps>
<Step>
Pick a category, type what you are looking for (for example `vegan bakery` or a business name), or both.
</Step>
<Step>
Type a city, neighborhood or address under **Where** to move the map there.
</Step>
<Step>
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.
</Step>
<Step>
Press **Search this area**. Pins appear on the map and the businesses fill the list below it.
</Step>
</Steps>
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/).
+1
View File
@@ -20,6 +20,7 @@
"advisor",
"---Contacts and inbox---",
"contacts-crm",
"lead-finder",
"segments",
"forms",
"website-tracking",
@@ -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 |
+3
View File
@@ -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
+608
View File
@@ -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)
}
+32
View File
@@ -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"))
{
+1
View File
@@ -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
+12
View File
@@ -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
+39
View File
@@ -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
+3
View File
@@ -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
+2
View File
@@ -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)
+107
View File
@@ -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
}
+348
View File
@@ -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 }
+709
View File
@@ -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(`(?:©|&copy;|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, "*")
}
+356
View File
@@ -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
}
+368
View File
@@ -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)
}
+216
View File
@@ -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
}
+140
View File
@@ -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
}
+146
View File
@@ -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
}
+230
View File
@@ -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
}
+42
View File
@@ -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))
}
+234
View File
@@ -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 := `<html><head><title>Bright Smiles Dental</title>
<meta name="description" content="Family dentist in Austin">
<meta name="viewport" content="width=device-width"></head>
<body>
<a href="mailto:Hello@BrightSmiles.com?subject=Hi">Email us</a>
<p>Billing: billing [at] brightsmiles [dot] com</p>
<span class="__cf_email__" data-cfemail="` + cfEncode("front@brightsmiles.com", 0x42) + `">[email protected]</span>
<img src="logo@2x.png">
<p>Sentry: 9f8e7d6c5b4a39281706f5e4d3c2b1a0@sentry.io</p>
<a href="tel:+1 (512) 555-0100">Call</a>
<a href="/contact-us">Contact</a>
<a href="https://www.facebook.com/brightsmiles">fb</a>
<script>var x = "nope@script.com";</script>
</body></html>`
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(`<html><head><meta name="generator" content="WordPress 6.1"></head><body>© 2018 Joe's Plumbing</body></html>`)
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)
}
}
}
+171
View File
@@ -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 ""
}
+303
View File
@@ -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)
}
+242
View File
@@ -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
}
+808
View File
@@ -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
}
+541
View File
@@ -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
}
+257
View File
@@ -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 := `<html><body>
<h2>Meet the Team</h2>
<div class="member"><h3>Jane Doe</h3><p>Owner &amp; Lead Dentist</p></div>
<div class="member"><h3>Dr. Ravi Patel, DMD</h3><p>Associate Dentist</p></div>
<div class="member"><span>Office Manager</span><h4>Carla Gómez</h4></div>
<p>Tom Baker – Head Hygienist</p>
<h3>Our Services</h3><p>Cleaning and whitening</p>
<h3>Austin Downtown</h3><p>Open Monday to Friday</p>
<a href="mailto:` + addr("jane", "brightsmiles.com") + `">Jane Doe</a>
<a href="https://www.linkedin.com/in/ravi-patel-4a1b2c">LinkedIn</a>
<script type="application/ld+json">{"@context":"https://schema.org","@type":"Dentist","employee":[
{"@type":"Person","name":"Sam Lee","jobTitle":"Practice Coordinator","email":"mailto:` + addr("sam.lee", "brightsmiles.com") + `"}]}</script>
</body></html>`
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 := `<html><body><h1>Impressum</h1>
<p>Zahnarztpraxis Sonnenschein GmbH<br>Hauptstraße 1, 10115 Berlin</p>
<p>Geschäftsführer: Dr. Max Mustermann und Erika Musterfrau</p>
<p>Registergericht: Amtsgericht Berlin</p></body></html>`
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])
}
}
+76
View File
@@ -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))
}
+679
View File
@@ -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
}
+199
View File
@@ -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)
}
+90
View File
@@ -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", `<html><body><p>Call us (208) 939-7053</p></body></html>`, true},
{"phone link", `<html><body><a href="tel:+12089397053">Call</a></body></html>`, true},
{"name and city", `<html><head><title>Moon Creek Dental | Boise dentist</title></head><body></body></html>`, true},
{"name elsewhere", `<html><head><title>Moon Creek Dental</title></head><body><p>Serving Portland, Oregon</p></body></html>`, false},
{"parked", `<html><body><h1>mooncreekdental.com is for sale</h1><p>Boise</p></body></html>`, false},
{"other number", `<html><body><p>Call (208) 555-0199. Boise.</p></body></html>`, 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(`<html><body><p>Moon Creek Dental, call 208-939-7053</p></body></html>`))
return
}
_, _ = w.Write([]byte(`<html><body><p>This domain is for sale</p></body></html>`))
}))
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)
}
}
+22
View File
@@ -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.",
@@ -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;
@@ -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;
+2
View File
@@ -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).
+5 -1
View File
@@ -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
+8
View File
@@ -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,
}
+365
View File
@@ -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"`
}
+1 -1
View File
@@ -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."},
+1 -1
View File
@@ -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()},
@@ -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)
}
}
+845
View File
@@ -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
}
+173
View File
@@ -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
}
+132
View File
@@ -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;
+151
View File
@@ -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" });
});
});
+1
View File
@@ -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",
+184
View File
@@ -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: {}
+4 -1
View File
@@ -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",
@@ -51,6 +51,33 @@ const FIELDS_BY_PROVIDER: Record<string, FieldDef[]> = {
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<string, string> = {
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.",
};
@@ -9,6 +9,18 @@ import { RAW_BRAND_LOGOS } from "./brandLogos";
import { GLYPH_DIMS, type GlyphSize } from "./glyphSize";
const BRAND_ICON: Record<string, { hex: string; path: string }> = {
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",
File diff suppressed because one or more lines are too long
@@ -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<GlyphSize, { tile: string; icon: string; text: string }> = {
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]" },
+786
View File
@@ -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<Prefs>) } : DEFAULT_PREFS;
} catch {
return DEFAULT_PREFS;
}
}
export default function LeadFinderPage() {
const config = useLeadFinderConfig();
if (!config.data) {
return (
<div className="flex h-full items-center justify-center bg-white">
{config.isError ? (
<p className="text-[12.5px] text-slate-500">{buildError(config.error as unknown as AppError)}</p>
) : (
<Loader2Icon className="size-5 animate-spin text-slate-300" />
)}
</div>
);
}
return <Finder config={config.data} />;
}
function Finder({ config }: { config: LeadFinderConfig }) {
const resolvedTheme = useAppStore((s) => s.resolvedTheme);
const confirm = useConfirm();
const [prefs, setPrefs] = useState<Prefs>(loadPrefs);
const patchPrefs = useCallback((p: Partial<Prefs>) => 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<LeadProvider>(() =>
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<LeadArea | null>(null);
// The last search's outline; drawn on the map, never searched again on its own.
const [searched, setSearched] = useState<LeadArea | null>(null);
const [tool, setTool] = useState<MapTool>("pan");
const [view, setView] = useState<MapView | null>(null);
const [fly, setFly] = useState<FlyTarget | null>(null);
const flyTo = (t: Omit<FlyTarget, "key">) => setFly({ ...t, key: Date.now() });
const controls = useRef<MapControls | null>(null);
// What the list and the map show.
const [searchId, setSearchId] = useState<string | null>(null);
const [refine, setRefine] = useState<Refine>(EMPTY_REFINE);
const [text, setText] = useState("");
const [sort, setSort] = useState<LeadSort>("score");
const [sideOpen, setSideOpen] = useState(false);
// Selection and detail.
const [selected, setSelected] = useState<Set<string>>(new Set());
const [allMatching, setAllMatching] = useState(false);
const [activeId, setActiveId] = useState<string | null>(null);
const [hoverId, setHoverId] = useState<string | null>(null);
const [dialog, setDialog] = useState<{ kind: "contacts" | "export"; selection: LeadSelection; count: number } | null>(null);
const lastClicked = useRef<string | null>(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 = (
<div className="flex h-full flex-col">
<div className="md:hidden shrink-0 h-11 px-3 flex items-center border-b border-slate-200">
<span className="text-[13px] font-semibold text-slate-900">Find businesses</span>
<button
type="button"
aria-label="Close panel"
onClick={() => setSideOpen(false)}
className="ml-auto size-7 rounded-md text-slate-500 hover:bg-slate-100 inline-flex items-center justify-center"
>
<XIcon className="size-3.5" />
</button>
</div>
<div className="flex-1 min-h-0 overflow-y-auto">
<motion.section
initial={{ opacity: 0, y: 6 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.24, ease: [0.22, 1, 0.36, 1] }}
className="px-3 pt-3 pb-4"
>
<SearchPanel
config={config}
query={query}
onQuery={setQuery}
category={category}
onCategory={setCategory}
location={location}
onLocation={setLocation}
onPlace={onPlace}
near={view && view.zoom >= 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}
/>
</motion.section>
<motion.section
initial={{ opacity: 0, y: 6 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.24, delay: 0.06, ease: [0.22, 1, 0.36, 1] }}
className="border-t border-slate-100 px-3 pt-3 pb-4"
>
<SavedSearches
config={config}
activeId={searchId}
onOpen={(s) => {
openSearch(s);
setSideOpen(false);
}}
onDelete={(id) => id === searchId && clearSearch()}
/>
</motion.section>
</div>
</div>
);
return (
<div className="relative flex h-full flex-col bg-white">
<header className="shrink-0 h-12 px-3 md:px-4 flex items-center gap-2 border-b border-slate-200">
<button
type="button"
aria-label="Find businesses"
onClick={() => setSideOpen(true)}
className="md:hidden size-7 rounded-md text-slate-600 hover:bg-slate-100 inline-flex items-center justify-center"
>
<PanelLeftIcon className="size-4" />
</button>
<MapPinnedIcon className="hidden md:block size-4 text-sky-600" />
<h1 className="text-[13.5px] font-semibold text-slate-900">Lead finder</h1>
<div className="h-4 w-px bg-slate-200" />
{currentSearch ? (
<span className="min-w-0 inline-flex h-6 items-center gap-1 rounded-md bg-sky-50 pl-2 pr-1 text-[12px] text-sky-800">
<span className="truncate max-w-[220px]">{currentSearch.name}</span>
<button
type="button"
aria-label="Show every lead"
title="Show every lead"
onClick={clearSearch}
className="size-4 rounded hover:bg-sky-100 inline-flex items-center justify-center"
>
<XIcon className="size-3" />
</button>
</span>
) : (
<span className="text-[12px] text-slate-500">All leads</span>
)}
{currentSearch?.has_more && (
<button
type="button"
onClick={loadMore}
disabled={search.isPending}
className="hidden sm:inline-flex h-6 items-center gap-1 rounded-md border border-slate-200 px-2 text-[11.5px] text-slate-600 hover:text-slate-900 disabled:opacity-50"
>
{search.isPending ? <Loader2Icon className="size-3 animate-spin" /> : <PlusIcon className="size-3" />}
Load more
</button>
)}
<div className="ml-auto inline-flex rounded-md border border-slate-200 p-0.5">
{(
[
["map", "Map", MapIcon],
["split", "Split", Columns2Icon],
["list", "List", ListIcon],
] as const
).map(([key, label, Icon]) => (
<button
key={key}
type="button"
aria-label={label}
aria-pressed={prefs.mode === key}
onClick={() => patchPrefs({ mode: key })}
className={cn("h-6 px-2 rounded inline-flex items-center gap-1 text-[11.5px]", prefs.mode === key ? "bg-slate-100 text-slate-900 font-medium" : "text-slate-500 hover:text-slate-900")}
>
<Icon className="size-3.5" />
<span className="hidden lg:inline">{label}</span>
</button>
))}
</div>
</header>
<div className="relative flex flex-1 min-h-0">
<aside className="hidden md:flex w-[316px] shrink-0 flex-col border-r border-slate-200 bg-white">{sidebar}</aside>
{sideOpen && <div className="md:hidden absolute inset-0 z-30 bg-white">{sidebar}</div>}
<div className="relative flex min-w-0 flex-1 flex-col">
<LeadFilterBar text={text} onText={setText} value={refine} onChange={setRefine} facets={facets.data} />
{!showList && <EnrichmentProgress runs={runList} searching={searchingLabel} />}
{showMap && (
<div className={cn("relative min-h-0", showList ? "h-[48%] lg:h-[56%] border-b border-slate-200" : "flex-1")}>
<LeadMap
styleUrl={styleUrl}
dark={darkMap}
themed={prefs.style !== "streets"}
controls={controls}
points={points.data?.data ?? []}
selected={highlight}
activeId={activeId}
colorBy={prefs.colorBy}
layer={prefs.layer}
area={shownArea}
tool={tool}
tilt={prefs.tilt}
initialView={prefs.view}
fly={fly}
onToolDone={() => setTool("pan")}
onArea={setArea}
onLasso={onLasso}
onPick={pickPoint}
onView={(v) => {
setView(v);
patchPrefs({ view: { center: v.center, zoom: v.zoom } });
}}
/>
<MapToolbar tool={tool} onTool={setTool} />
<MapControlsBar
prefs={prefs}
onPrefs={patchPrefs}
onZoom={(d) => 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" && <ToolHint tool={tool} onCancel={() => setTool("pan")} />}
{tool === "pan" && !blockedReason && (
<div className="absolute left-1/2 top-3 z-10 -translate-x-1/2">
<button
type="button"
onClick={runSearch}
disabled={search.isPending}
className="h-8 px-3.5 rounded-full bg-white/95 border border-slate-200 text-[12px] font-medium text-slate-800 shadow-[0_6px_18px_-8px_rgba(15,23,42,0.35)] backdrop-blur inline-flex items-center gap-1.5 hover:text-sky-700 disabled:opacity-60"
>
{search.isPending ? <Loader2Icon className="size-3.5 animate-spin text-sky-600" /> : <RotateCw className="size-3.5 text-sky-600" />}
{area ? "Search this area" : "Search this view"}
</button>
</div>
)}
<Legend colorBy={prefs.colorBy} layer={prefs.layer} count={points.data?.data.length ?? 0} truncated={!!points.data?.truncated} />
{points.isFetching && (
<div className="absolute left-3 bottom-12 z-10 inline-flex items-center gap-1.5 rounded-full bg-white/90 px-2 py-1 text-[11px] text-slate-500 shadow-sm">
<Loader2Icon className="size-3 animate-spin" />
Updating pins
</div>
)}
{!searchId && (points.data?.data.length ?? 0) === 0 && !points.isPending && <EmptyHint />}
</div>
)}
{showList && (
<div className="relative min-h-0 flex-1">
<LeadsTable
leads={leads}
total={total}
loading={list.isPending || (list.isError && list.isFetching && !leads.length)}
error={list.isError && !leads.length ? buildError(list.error as unknown as AppError) : null}
onRetry={() => 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={<EnrichmentProgress runs={runList} searching={searchingLabel} />}
/>
</div>
)}
<LeadDrawer
id={activeId}
config={config}
onClose={() => setActiveId(null)}
onAddToContacts={(id) => setDialog({ kind: "contacts", selection: { lead_ids: [id] }, count: 1 })}
/>
</div>
</div>
<LeadSelectionBar
count={selectedCount}
enrichCost={config.enrich_cost}
enriching={enrich.isPending}
onEnrich={() => startEnrich(selection)}
onAddToContacts={() => setDialog({ kind: "contacts", selection, count: selectedCount })}
onExport={() => setDialog({ kind: "export", selection, count: selectedCount })}
onStatus={setStatus}
onTag={addTag}
onDelete={deleteSelected}
onClear={clearSelection}
/>
<AddToContactsDialog
open={dialog?.kind === "contacts"}
onClose={() => setDialog(null)}
selection={dialog?.selection ?? {}}
count={dialog?.count ?? 0}
suggestedSegment={currentSearch?.name}
/>
<ExportDialog open={dialog?.kind === "export"} onClose={() => setDialog(null)} selection={dialog?.selection ?? {}} count={dialog?.count ?? 0} config={config} />
</div>
);
}
const TOOLS: { id: MapTool; label: string; icon: React.ReactNode }[] = [
{ id: "pan", label: "Move the map", icon: <HandIcon className="size-3.5" /> },
{ id: "rect", label: "Draw a rectangle to search", icon: <SquareIcon className="size-3.5" /> },
{ id: "circle", label: "Draw a circle to search", icon: <CircleIcon className="size-3.5" /> },
{ id: "polygon", label: "Draw a shape to search", icon: <PentagonIcon className="size-3.5" /> },
{ id: "lasso", label: "Lasso leads to select them", icon: <LassoIcon className="size-3.5" /> },
];
function MapToolbar({ tool, onTool }: { tool: MapTool; onTool: (t: MapTool) => void }) {
return (
<div className="absolute left-3 top-3 z-10 flex flex-col gap-0.5 rounded-lg border border-slate-200 bg-white/95 p-0.5 shadow-[0_6px_18px_-8px_rgba(15,23,42,0.3)] backdrop-blur">
{TOOLS.map((t) => (
<button
key={t.id}
type="button"
title={t.label}
aria-label={t.label}
aria-pressed={tool === t.id}
onClick={() => onTool(t.id)}
className={cn("size-7 rounded-md inline-flex items-center justify-center transition-colors", tool === t.id ? "bg-sky-600 text-white" : "text-slate-600 hover:bg-slate-100 hover:text-slate-900")}
>
{t.icon}
</button>
))}
</div>
);
}
const HINTS: Record<Exclude<MapTool, "pan">, 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<MapTool, "pan">; onCancel: () => void }) {
return (
<div className="absolute left-1/2 top-3 z-10 -translate-x-1/2 inline-flex items-center gap-2 rounded-full bg-slate-900/90 py-1 pl-3 pr-1 text-[12px] text-white shadow-lg">
{HINTS[tool]}
<button type="button" onClick={onCancel} className="h-6 rounded-full bg-white/15 px-2 text-[11.5px] hover:bg-white/25">
Esc
</button>
</div>
);
}
function MapControlsBar({ prefs, onPrefs, onZoom, onFit }: { prefs: Prefs; onPrefs: (p: Partial<Prefs>) => 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 ? <CheckIcon className="size-3.5 text-sky-600" /> : undefined);
return (
<div className="absolute right-3 top-3 z-10 flex flex-col gap-1.5">
<div className="flex flex-col gap-0.5 rounded-lg border border-slate-200 bg-white/95 p-0.5 shadow-[0_6px_18px_-8px_rgba(15,23,42,0.3)] backdrop-blur">
<PopoverMenu align="end">
<PopoverMenuTrigger asChild>
<button type="button" title="Map layers" aria-label="Map layers" className={btn}>
<LayersIcon className="size-3.5" />
</button>
</PopoverMenuTrigger>
<PopoverMenuContent minWidth={220}>
<PopoverMenuLabel>Show leads as</PopoverMenuLabel>
<PopoverMenuItem onSelect={() => onPrefs({ layer: "pins" })} trailing={check(prefs.layer === "pins")}>
Pins
</PopoverMenuItem>
<PopoverMenuItem onSelect={() => onPrefs({ layer: "heat" })} trailing={check(prefs.layer === "heat")}>
Heatmap
</PopoverMenuItem>
<PopoverMenuSeparator />
<PopoverMenuLabel>Color pins by</PopoverMenuLabel>
{(
[
["reach", "Reachability"],
["status", "Status"],
["score", "Score"],
["rating", "Rating"],
] as const
).map(([id, label]) => (
<PopoverMenuItem key={id} onSelect={() => onPrefs({ colorBy: id })} trailing={check(prefs.colorBy === id)}>
{label}
</PopoverMenuItem>
))}
<PopoverMenuSeparator />
<PopoverMenuLabel>Map style</PopoverMenuLabel>
{(
[
["auto", "Match the dashboard"],
["light", "Light"],
["dark", "Dark"],
["streets", "Streets"],
] as const
).map(([id, label]) => (
<PopoverMenuItem key={id} onSelect={() => onPrefs({ style: id })} trailing={check(prefs.style === id)}>
{label}
</PopoverMenuItem>
))}
</PopoverMenuContent>
</PopoverMenu>
<button type="button" title={prefs.tilt ? "Flat view" : "Tilted 3D view"} aria-label="Toggle tilted view" aria-pressed={prefs.tilt} onClick={() => onPrefs({ tilt: !prefs.tilt })} className={cn(btn, prefs.tilt && "text-sky-700 bg-sky-50")}>
<BoxIcon className="size-3.5" />
</button>
<button type="button" title="Fit to the leads" aria-label="Fit to the leads" onClick={onFit} className={btn}>
<FocusIcon className="size-3.5" />
</button>
</div>
<div className="flex flex-col gap-0.5 rounded-lg border border-slate-200 bg-white/95 p-0.5 shadow-[0_6px_18px_-8px_rgba(15,23,42,0.3)] backdrop-blur">
<button type="button" aria-label="Zoom in" onClick={() => onZoom(1)} className={btn}>
<PlusIcon className="size-3.5" />
</button>
<button type="button" aria-label="Zoom out" onClick={() => onZoom(-1)} className={btn}>
<MinusIcon className="size-3.5" />
</button>
</div>
</div>
);
}
function Legend({ colorBy, layer, count, truncated }: { colorBy: ColorBy; layer: MapLayerMode; count: number; truncated: boolean }) {
return (
<div className="absolute left-3 bottom-3 z-10 flex flex-wrap items-center gap-x-2.5 gap-y-1 rounded-lg border border-slate-200 bg-white/95 px-2.5 py-1.5 text-[11px] text-slate-600 shadow-sm backdrop-blur max-w-[calc(100%-300px)] min-w-[180px]">
<span className="font-medium tabular-nums text-slate-900">
{count.toLocaleString()}
{truncated ? "+" : ""} on map
</span>
{layer === "pins" &&
LEGEND[colorBy].map((l) => (
<span key={l.label} className="inline-flex items-center gap-1">
<span className="size-2 rounded-full" style={{ background: l.color }} />
{l.label}
</span>
))}
{layer === "heat" && <span>Brighter where leads are denser and better</span>}
</div>
);
}
function EmptyHint() {
return (
<div className="pointer-events-none absolute inset-0 z-[5] flex items-center justify-center p-6">
<div className="max-w-[340px] rounded-xl border border-slate-200 bg-white/95 px-5 py-4 text-center shadow-[0_16px_40px_-20px_rgba(15,23,42,0.4)] backdrop-blur">
<MapPinnedIcon className="mx-auto size-6 text-sky-600" />
<p className="mt-2 text-[13px] font-semibold text-slate-900">Find businesses on the map</p>
<p className="mt-1 text-[12px] leading-relaxed text-slate-500">
Pick a category, go to a city, then search the view or draw the exact area. Find people and emails reads each business&apos;s own website for who runs it and how to reach them.
</p>
</div>
</div>
);
}
@@ -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:
@@ -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<LeadContactsWho>("business");
const [segmentIds, setSegmentIds] = useState<string[]>([]);
const [categoryIds, setCategoryIds] = useState<string[]>([]);
const [campaignIds, setCampaignIds] = useState<string[]>([]);
const [skipActive, setSkipActive] = useState(true);
const [verifiedOnly, setVerifiedOnly] = useState(false);
const [includeGuessed, setIncludeGuessed] = useState(false);
const [keepExisting, setKeepExisting] = useState(false);
const [result, setResult] = useState<AddLeadsToContactsResult | null>(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 (
<LeadDialog
open={open}
onClose={close}
width={600}
icon={<UserPlusIcon className="size-3" />}
eyebrow="Add to contacts"
title={`${count.toLocaleString()} lead${count === 1 ? "" : "s"}`}
footer={
result ? (
<>
<Link to="/app/contacts" onClick={close} className="h-7 px-3 rounded-md text-[12px] text-slate-600 hover:text-slate-900 inline-flex items-center gap-1">
Open contacts
<ArrowRightIcon className="size-3" />
</Link>
<button type="button" onClick={close} className="h-7 px-3 rounded-md bg-slate-900 text-white text-[12px] font-medium">
Done
</button>
</>
) : (
<>
<button type="button" onClick={close} className="h-7 px-3 rounded-md text-[12px] text-slate-600 hover:text-slate-900">
Cancel
</button>
<button
type="button"
onClick={submit}
disabled={add.isPending}
className="h-7 px-3 rounded-md bg-sky-600 text-white text-[12px] font-medium inline-flex items-center gap-1.5 hover:bg-sky-700 disabled:opacity-60"
>
{add.isPending ? <Loader2Icon className="size-3.5 animate-spin" /> : <UserPlusIcon className="size-3.5" />}
Add to contacts
</button>
</>
)
}
>
{result ? (
<Outcome result={result} who={who} keepExisting={keepExisting} />
) : (
<div className="px-4 py-4 space-y-4">
<section>
<SectionLabel>Who to add</SectionLabel>
<div className="grid grid-cols-3 gap-2">
{WHO.map((w) => {
const on = who === w.id;
return (
<button
key={w.id}
type="button"
onClick={() => setWho(w.id)}
aria-pressed={on}
className={cn(
"rounded-md border px-2.5 py-2 text-left transition-colors",
on ? "border-sky-300 bg-sky-50/70 ring-2 ring-sky-100" : "border-slate-200 hover:border-slate-300",
)}
>
<w.icon className={cn("size-3.5", on ? "text-sky-600" : "text-slate-400")} />
<div className={cn("mt-1 text-[12px] font-medium", on ? "text-sky-900" : "text-slate-900")}>{w.label}</div>
<div className="text-[10.5px] leading-snug text-slate-500">{w.hint}</div>
</button>
);
})}
</div>
<p className="mt-2 text-[11.5px] leading-relaxed text-slate-500">
{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.
</p>
</section>
<section className="rounded-lg border border-slate-200 divide-y divide-slate-100">
<div className="px-4 pt-3 pb-2">
<h2 className="text-[12.5px] font-medium text-slate-900">Add them to</h2>
<p className="text-[11.5px] text-slate-500">Optional. Every contact made from this selection gets these.</p>
</div>
<Row icon={FolderTreeIcon} label="Segments" hint="A list you can send a campaign to">
<SegmentMultiPicker value={segmentIds} onChange={setSegmentIds} allowCreate suggestedName={suggestedSegment} placeholder="Pick or create a segment…" />
</Row>
<Row icon={TagsIcon} label="Labels" hint="To filter and segment by">
<CategoryPicker value={categoryIds} onChange={setCategoryIds} />
</Row>
<Row icon={MegaphoneIcon} label="Campaigns" hint="Enrolled as leads; an active campaign starts emailing them">
<CampaignMultiPicker value={campaignIds} onChange={setCampaignIds} />
{campaignIds.length > 0 && (
<label className="mt-2 flex items-start gap-1.5 text-[11.5px] text-slate-700 cursor-pointer select-none">
<Checkbox tone="slate" className="mt-px" checked={skipActive} onChange={(e) => setSkipActive(e.target.checked)} />
<span>
Skip contacts already running in another campaign
<span className="block text-slate-500">They are still added, just not enrolled while another campaign is emailing them.</span>
</span>
</label>
)}
</Row>
</section>
<section className="rounded-lg border border-slate-200 divide-y divide-slate-100">
<Option title="Only verified addresses" hint="Leave out every address that did not check as valid.">
<Toggle value={verifiedOnly} onChange={setVerifiedOnly} ariaLabel="Only verified addresses" />
</Option>
{who !== "business" && !verifiedOnly && (
<Option title="Include unconfirmed guesses" hint="Addresses worked out from a name that the mail server could not confirm. They can bounce.">
<Toggle value={includeGuessed} onChange={setIncludeGuessed} ariaLabel="Include unconfirmed guesses" />
</Option>
)}
<Option
title="Contacts you already have"
hint={keepExisting ? "Left as they are. They still get the segments, labels and campaigns above." : "Empty details are filled in from the lead. Nothing they already have is erased."}
>
<div className="inline-flex shrink-0 rounded-md border border-slate-200 p-0.5">
{(
[
[false, "Update details"],
[true, "Leave as is"],
] as const
).map(([keep, label]) => (
<button
key={label}
type="button"
aria-pressed={keepExisting === keep}
onClick={() => setKeepExisting(keep)}
className={cn("h-6 px-2 rounded text-[11.5px] whitespace-nowrap", keepExisting === keep ? "bg-slate-100 text-slate-900 font-medium" : "text-slate-500 hover:text-slate-900")}
>
{label}
</button>
))}
</div>
</Option>
</section>
</div>
)}
</LeadDialog>
);
}
function Outcome({ result, who, keepExisting }: { result: AddLeadsToContactsResult; who: LeadContactsWho; keepExisting: boolean }) {
const added = result.imported + result.updated;
return (
<div className="px-4 py-4">
<div className="flex items-center gap-3 rounded-lg border border-emerald-200 bg-emerald-50/60 px-3.5 py-3">
<div className="size-8 rounded-full bg-emerald-100 text-emerald-700 inline-flex items-center justify-center">
<UserPlusIcon className="size-4" />
</div>
<div>
<div className="text-[13px] font-semibold text-slate-900">
{added.toLocaleString()} contact{added === 1 ? "" : "s"} added
</div>
<div className="text-[11.5px] text-slate-600">
{result.imported.toLocaleString()} new, {result.updated.toLocaleString()} updated
</div>
</div>
</div>
<dl className="mt-3 grid grid-cols-2 sm:grid-cols-3 gap-2">
<Stat label="No email yet" value={result.no_email} />
<Stat label="Not verified" value={result.unverified} />
{who !== "business" && <Stat label="Unconfirmed guesses left out" value={result.guessed} />}
<Stat label="Suppressed" value={result.suppressed} />
<Stat label={keepExisting ? "Already contacts, left as is" : "Skipped"} value={result.skipped} />
{result.failed > 0 && <Stat label="Failed" value={result.failed} tone="text-rose-700" />}
</dl>
{result.no_email > 0 && (
<p className="mt-3 text-[11.5px] text-slate-500">Anyone without an email stays in the finder. Run Find people and emails on them, then add them again.</p>
)}
</div>
);
}
function SectionLabel({ children }: { children: React.ReactNode }) {
return <div className="mb-1.5 text-[10px] uppercase tracking-[0.14em] font-medium text-slate-400">{children}</div>;
}
function Row({ icon: Icon, label, hint, children }: { icon: LucideIcon; label: string; hint: string; children: React.ReactNode }) {
return (
<div className="px-4 py-3 grid grid-cols-1 sm:grid-cols-[160px_minmax(0,1fr)] gap-x-4 gap-y-1.5 items-start">
<div className="flex items-start gap-2 pt-1">
<Icon className="size-3.5 text-slate-400 mt-px shrink-0" />
<div className="min-w-0">
<p className="text-[12px] font-medium text-slate-800">{label}</p>
<p className="text-[11px] text-slate-400 leading-snug">{hint}</p>
</div>
</div>
<div className="min-w-0">{children}</div>
</div>
);
}
function Option({ title, hint, children }: { title: string; hint: string; children: React.ReactNode }) {
return (
<div className="flex items-center justify-between gap-3 px-4 py-2.5">
<div className="min-w-0">
<div className="text-[12px] font-medium text-slate-800">{title}</div>
<div className="text-[11px] text-slate-500">{hint}</div>
</div>
{children}
</div>
);
}
function Stat({ label, value, tone }: { label: string; value: number; tone?: string }) {
return (
<div className="rounded-md border border-slate-200 px-3 py-2">
<dt className="text-[11px] text-slate-500">{label}</dt>
<dd className={cn("text-[15px] font-semibold tabular-nums", tone ?? "text-slate-900")}>{value.toLocaleString()}</dd>
</div>
);
}
@@ -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<string, string>());
const [finished, setFinished] = useState<LeadEnrichmentRun[]>([]);
// 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 (
<AnimatePresence initial={false}>
{searching && (
<Strip key="search">
<span className="campaign-grid text-sky-600 shrink-0" aria-hidden />
<span className="text-shimmer truncate font-medium text-sky-800">{searching}</span>
<Track>
<span className="absolute inset-y-0 w-1/3 rounded-full bg-sky-500 progress-sweep" />
</Track>
</Strip>
)}
{active.length > 0 && (
<Strip key="runs">
<span className="campaign-grid text-sky-600 shrink-0" aria-hidden />
<span className="text-shimmer shrink-0 font-medium text-sky-800">Finding people and emails</span>
<span className="truncate text-slate-500 tabular-nums">
{processed.toLocaleString()} of {total.toLocaleString()} businesses
{emails > 0 && ` · ${emails.toLocaleString()} with an email`}
{people > 0 && ` · ${people.toLocaleString()} ${people === 1 ? "person" : "people"}`}
</span>
<span className="ml-auto hidden sm:inline shrink-0 text-[11px] text-slate-400">Keeps going if you leave</span>
<span className="shrink-0 w-8 text-right tabular-nums text-[11px] font-medium text-sky-700">{pct}%</span>
<Track>
<span className="absolute inset-y-0 left-0 rounded-full bg-sky-500 transition-[width] duration-700" style={{ width: `${Math.max(3, pct)}%` }} />
<span className="absolute inset-y-0 w-1/4 rounded-full bg-white/60 progress-sweep" />
</Track>
</Strip>
)}
{finished.map((r) => {
const failed = r.status === "error";
return (
<Strip key={r.id} tone={failed ? "amber" : "emerald"}>
{failed ? <TriangleAlertIcon className="size-3.5 shrink-0 text-amber-600" /> : <CheckCircle2Icon className="size-3.5 shrink-0 text-emerald-600" />}
<span className={cn("shrink-0 font-medium", failed ? "text-amber-800" : "text-emerald-800")}>{failed ? "Stopped early" : "Done"}</span>
<span className="truncate text-slate-600">
{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"}`}
</span>
<button
type="button"
aria-label="Dismiss"
onClick={() => setFinished((cur) => cur.filter((x) => x.id !== r.id))}
className="ml-auto size-5 shrink-0 rounded text-slate-400 hover:text-slate-700 hover:bg-white/70 inline-flex items-center justify-center"
>
<XIcon className="size-3" />
</button>
</Strip>
);
})}
</AnimatePresence>
);
}
function Strip({ children, tone = "sky" }: { children: React.ReactNode; tone?: "sky" | "emerald" | "amber" }) {
return (
<motion.div
initial={{ height: 0, opacity: 0 }}
animate={{ height: "auto", opacity: 1 }}
exit={{ height: 0, opacity: 0 }}
transition={{ duration: 0.2, ease: [0.22, 1, 0.36, 1] }}
className="shrink-0 overflow-hidden"
>
<div
className={cn(
"relative h-9 px-3 flex items-center gap-2 border-b text-[12px]",
tone === "sky" && "border-sky-100 bg-sky-50/50",
tone === "emerald" && "border-emerald-100 bg-emerald-50/50",
tone === "amber" && "border-amber-100 bg-amber-50/60",
)}
role="status"
>
{children}
</div>
</motion.div>
);
}
function Track({ children }: { children: React.ReactNode }) {
return <div className="absolute inset-x-0 bottom-0 h-0.5 overflow-hidden bg-sky-100">{children}</div>;
}
@@ -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<LeadExportFormat>("csv");
const [rows, setRows] = useState<LeadExportRows>("leads");
const [columns, setColumns] = useState<string[]>(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 (
<LeadDialog
open={open}
onClose={onClose}
icon={<DownloadIcon className="size-3" />}
eyebrow="Export"
title={`${count.toLocaleString()} lead${count === 1 ? "" : "s"}`}
width={560}
footer={
<>
<span className="mr-auto text-[11px] text-slate-400">
{rows === "people" ? `${config.person_columns.length} person columns + ${sent.length}` : `${sent.length} columns`}
</span>
<button type="button" onClick={onClose} className="h-7 px-3 rounded-md text-[12px] text-slate-600 hover:text-slate-900">
Cancel
</button>
<button
type="button"
onClick={run}
disabled={busy || sent.length === 0}
className="h-7 px-3 rounded-md bg-sky-600 text-white text-[12px] font-medium inline-flex items-center gap-1.5 hover:bg-sky-700 disabled:opacity-60"
>
{busy ? <Loader2Icon className="size-3.5 animate-spin" /> : <DownloadIcon className="size-3.5" />}
Download
</button>
</>
}
>
<div className="px-4 py-4 space-y-4">
<div className="grid grid-cols-2 gap-2">
{ROWS.map((r) => (
<button
key={r.id}
type="button"
onClick={() => setRows(r.id)}
aria-pressed={rows === r.id}
className={cn(
"rounded-md border px-3 py-2 text-left transition-colors",
rows === r.id ? "border-sky-300 bg-sky-50" : "border-slate-200 hover:border-slate-300",
)}
>
<div className={cn("text-[12.5px] font-medium", rows === r.id ? "text-sky-800" : "text-slate-900")}>{r.label}</div>
<div className="text-[11px] text-slate-500">{r.hint}</div>
</button>
))}
</div>
<div className="grid grid-cols-3 gap-2">
{FORMATS.map((f) => (
<button
key={f.id}
type="button"
onClick={() => setFormat(f.id)}
aria-pressed={format === f.id}
className={cn(
"rounded-md border px-3 py-2 text-left transition-colors",
format === f.id ? "border-sky-300 bg-sky-50" : "border-slate-200 hover:border-slate-300",
)}
>
<div className={cn("text-[12.5px] font-medium", format === f.id ? "text-sky-800" : "text-slate-900")}>{f.label}</div>
<div className="text-[11px] text-slate-500">{f.hint}</div>
</button>
))}
</div>
<div>
<div className="mb-1.5 flex items-center">
<span className="text-[10px] font-medium uppercase tracking-[0.14em] text-slate-400">{rows === "people" ? "Business columns" : "Columns"}</span>
<button type="button" onClick={() => setColumns(config.export_columns.map((c) => c.key))} className="ml-auto text-[11px] text-sky-700 hover:underline">
All
</button>
<span className="mx-1.5 text-slate-300">·</span>
<button type="button" onClick={() => setColumns(config.default_export_columns)} className="text-[11px] text-sky-700 hover:underline">
Default
</button>
</div>
<div className="grid grid-cols-2 sm:grid-cols-3 gap-x-3 gap-y-1">
{config.export_columns.filter((c) => rows === "leads" || c.key !== "people").map((c) => (
<label key={c.key} className="flex items-center gap-2 py-0.5 text-[12px] text-slate-700 cursor-pointer">
<Checkbox tone="slate" checked={columns.includes(c.key)} onChange={() => toggle(c.key)} />
{c.label}
</label>
))}
</div>
{rows === "people" && (
<p className="mt-2 text-[11px] text-slate-400">
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.
</p>
)}
</div>
</div>
</LeadDialog>
);
}
@@ -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 extends keyof Refine>(k: K, v: Refine[K]) => onChange({ ...value, [k]: v });
const toggle = <T,>(list: T[], v: T) => (list.includes(v) ? list.filter((x) => x !== v) : [...list, v]);
const count = refineCount(value);
return (
<div className="space-y-3.5">
<div className="flex items-center">
<span className="text-[10px] font-medium uppercase tracking-[0.14em] text-slate-400">Refine results</span>
{count > 0 && (
<button
type="button"
onClick={() => onChange(EMPTY_REFINE)}
className="ml-auto inline-flex items-center gap-1 text-[11px] text-slate-500 hover:text-slate-900"
>
<RotateCcwIcon className="size-3" />
Reset
</button>
)}
</div>
<Group label="Reachability">
{REACH.map((r) => (
<Pill key={r.id} on={value.reach.includes(r.id)} onClick={() => {
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}
</Pill>
))}
</Group>
<Group label="Rating">
<div className="inline-flex rounded-md border border-slate-200 p-0.5">
{RATINGS.map((r) => (
<button
key={r.label}
type="button"
onClick={() => set("minRating", r.v)}
className={cn(
"h-6 px-2 rounded text-[11.5px]",
value.minRating === r.v ? "bg-sky-50 text-sky-700 font-medium" : "text-slate-500 hover:text-slate-900",
)}
>
{r.label}
</button>
))}
</div>
</Group>
<div className="grid grid-cols-3 gap-2">
<NumField label="Min reviews" value={value.minReviews} onChange={(v) => set("minReviews", v)} />
<NumField label="Max reviews" value={value.maxReviews} onChange={(v) => set("maxReviews", v)} />
<NumField label="Min score" value={value.minScore} onChange={(v) => set("minScore", Math.min(100, v))} />
</div>
<Group label="Status">
{STATUSES.map((s) => (
<Pill key={s.id} on={value.statuses.includes(s.id)} onClick={() => set("statuses", toggle(value.statuses, s.id))}>
{s.label}
</Pill>
))}
</Group>
{facets && facets.categories.length > 1 && (
<Group label="Category">
{facets.categories.slice(0, 12).map((c) => (
<Pill key={c.value} on={value.category === c.value} onClick={() => set("category", value.category === c.value ? "" : c.value)}>
{c.value}
<span className="text-slate-400">{c.count}</span>
</Pill>
))}
</Group>
)}
{facets && facets.tags.length > 0 && (
<Group label="Tag">
{facets.tags.map((t) => (
<Pill key={t.value} on={value.tag === t.value} onClick={() => set("tag", value.tag === t.value ? "" : t.value)}>
{t.value}
<span className="text-slate-400">{t.count}</span>
</Pill>
))}
</Group>
)}
<div className="space-y-2">
<Switch label="Only what's in the map view" value={value.inView} onChange={(v) => set("inView", v)} />
<Switch label="Hide leads already in contacts" value={value.hideContacts} onChange={(v) => set("hideContacts", v)} />
<Switch label="Hide chains and franchises" value={value.excludeChains} onChange={(v) => set("excludeChains", v)} />
<Switch
label="Hide dismissed leads"
value={value.hideDismissed && value.statuses.length === 0}
disabled={value.statuses.length > 0}
onChange={(v) => set("hideDismissed", v)}
/>
</div>
</div>
);
}
function Group({ label, children }: { label: string; children: React.ReactNode }) {
return (
<div>
<div className="mb-1.5 text-[11.5px] text-slate-500">{label}</div>
<div className="flex flex-wrap gap-1">{children}</div>
</div>
);
}
function Pill({ on, onClick, children }: { on: boolean; onClick: () => void; children: React.ReactNode }) {
return (
<button
type="button"
aria-pressed={on}
onClick={onClick}
className={cn(
"h-6 px-2 rounded-md border text-[11.5px] inline-flex items-center gap-1 transition-colors",
on ? "border-sky-300 bg-sky-50 text-sky-700" : "border-slate-200 text-slate-600 hover:border-slate-300 hover:text-slate-900",
)}
>
{children}
</button>
);
}
function NumField({ label, value, onChange }: { label: string; value: number; onChange: (v: number) => void }) {
return (
<label className="block">
<span className="mb-1 block text-[11px] text-slate-500">{label}</span>
<NumberInput value={value} onChange={(v) => onChange(Math.max(0, Math.round(v || 0)))} min={0} placeholder="Any" />
</label>
);
}
function Switch({ label, value, onChange, disabled }: { label: string; value: boolean; onChange: (v: boolean) => void; disabled?: boolean }) {
return (
<div className={cn("flex items-center justify-between gap-2", disabled && "opacity-50")}>
<span className="text-[12px] text-slate-700">{label}</span>
<Toggle value={value} onChange={onChange} disabled={disabled} ariaLabel={label} />
</div>
);
}
@@ -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 (
<AnimatePresence>
{open && (
<motion.div
key="overlay"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.15 }}
onMouseDown={onClose}
className="fixed inset-0 z-[120] flex items-center justify-center bg-slate-900/30 backdrop-blur-[2px] px-4"
>
<motion.div
key="card"
role="dialog"
aria-modal="true"
aria-label={title}
initial={{ y: 8, opacity: 0, scale: 0.985 }}
animate={{ y: 0, opacity: 1, scale: 1 }}
exit={{ y: 8, opacity: 0, scale: 0.985 }}
transition={{ duration: 0.18, ease: [0.22, 1, 0.36, 1] }}
onMouseDown={(e) => 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]"
>
<header className="h-12 px-4 border-b border-slate-200 flex items-center gap-2.5 shrink-0">
<div className="size-5 rounded bg-slate-100 text-slate-600 flex items-center justify-center">{icon}</div>
<span className="text-[10px] uppercase tracking-[0.14em] text-slate-400 font-medium">{eyebrow}</span>
<div className="h-4 w-px bg-slate-200" />
<span className="text-[12.5px] text-slate-900 font-medium truncate">{title}</span>
<button
type="button"
onClick={onClose}
aria-label="Close"
className="ml-auto size-7 rounded-md text-slate-500 hover:text-slate-900 hover:bg-slate-100 inline-flex items-center justify-center transition-colors"
>
<XIcon className="w-3.5 h-3.5" />
</button>
</header>
<div className="flex-1 min-h-0 overflow-y-auto">{children}</div>
<footer className="px-4 py-3 border-t border-slate-200 flex items-center justify-end gap-2 shrink-0 bg-slate-50/60">{footer}</footer>
</motion.div>
</motion.div>
)}
</AnimatePresence>
);
}
+572
View File
@@ -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<string, string> = {
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<Tab>("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 (
<AnimatePresence>
{id && (
<motion.aside
key="drawer"
initial={{ x: 24, opacity: 0 }}
animate={{ x: 0, opacity: 1 }}
exit={{ x: 24, opacity: 0 }}
transition={{ duration: 0.18, ease: [0.22, 1, 0.36, 1] }}
className="absolute inset-y-0 right-0 z-20 flex w-full sm:w-[400px] flex-col border-l border-slate-200 bg-white shadow-[-16px_0_40px_-24px_rgba(15,23,42,0.35)]"
aria-label="Lead details"
>
{!lead.data ? (
<div className="flex flex-1 items-center justify-center">
{lead.isError ? (
<p className="text-[12px] text-slate-500">This lead is no longer here.</p>
) : (
<Loader2Icon className="size-5 animate-spin text-slate-300" />
)}
</div>
) : (
<Body lead={lead.data} config={config} tab={tab} onTab={setTab} onClose={onClose} onAddToContacts={onAddToContacts} />
)}
</motion.aside>
)}
</AnimatePresence>
);
}
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 (
<>
<header className="shrink-0 px-4 pt-3 pb-2.5 border-b border-slate-200">
<div className="flex items-start gap-2">
<div className="mt-0.5 size-8 shrink-0 rounded-md bg-sky-50 text-sky-700 flex items-center justify-center">
<BuildingIcon className="size-4" />
</div>
<div className="min-w-0 flex-1">
<h2 className="truncate text-[14px] font-semibold text-slate-900">{lead.name}</h2>
<p className="truncate text-[11.5px] text-slate-500">{[lead.category, lead.city].filter(Boolean).join(" · ") || provider}</p>
</div>
<ResourceViewers resource={`lead:${lead.id}`} />
<button
type="button"
aria-label="Close"
onClick={onClose}
className="size-7 rounded-md text-slate-500 hover:text-slate-900 hover:bg-slate-100 inline-flex items-center justify-center"
>
<XIcon className="size-3.5" />
</button>
</div>
<div className="mt-2.5 flex items-center gap-1.5">
<div className="inline-flex rounded-md border border-slate-200 p-0.5">
{(["new", "saved", "contacted", "dismissed"] as LeadStatus[]).map((s) => (
<button
key={s}
type="button"
onClick={() => setStatus(s)}
className={cn(
"h-6 px-2 rounded text-[11.5px] transition-colors",
lead.status === s ? "bg-sky-50 text-sky-700 font-medium" : "text-slate-500 hover:text-slate-900",
)}
>
{STATUS_LABEL[s]}
</button>
))}
</div>
<div className="ml-auto w-[72px]">
<ScoreBar score={lead.score} />
</div>
</div>
<div className="mt-2.5 flex flex-wrap items-center gap-1.5">
<button
type="button"
onClick={findEmails}
disabled={enrich.isPending || lead.enrichment_status === "queued"}
className="h-7 px-2.5 rounded-md bg-sky-600 text-white text-[12px] font-medium inline-flex items-center gap-1.5 hover:bg-sky-700 disabled:opacity-60"
>
{lead.enrichment_status === "queued" ? (
<span className="campaign-grid text-white" aria-hidden />
) : enrich.isPending ? (
<Loader2Icon className="size-3.5 animate-spin" />
) : (
<SparklesIcon className="size-3.5" />
)}
{lead.enrichment_status === "queued" ? (lead.website ? "Reading website…" : "Looking for a website…") : lead.enriched_at ? "Read again" : "Find people and emails"}
</button>
{lead.contact_id ? (
<Link
to="/app/contacts"
className="h-7 px-2.5 rounded-md border border-emerald-200 bg-emerald-50 text-emerald-700 text-[12px] font-medium inline-flex items-center gap-1.5"
>
<CheckIcon className="size-3.5" />
In contacts
</Link>
) : (
<button
type="button"
onClick={() => onAddToContacts(lead.id)}
disabled={!reachable}
title={reachable ? undefined : "Find an email first"}
className="h-7 px-2.5 rounded-md border border-slate-200 bg-white text-slate-700 text-[12px] font-medium inline-flex items-center gap-1.5 hover:border-slate-300 hover:text-slate-900 disabled:opacity-50"
>
<UserPlusIcon className="size-3.5" />
Add to contacts
</button>
)}
{lead.website && (
<a href={lead.website} target="_blank" rel="noopener noreferrer nofollow" className="h-7 px-2 rounded-md border border-slate-200 text-slate-600 hover:text-slate-900 inline-flex items-center gap-1 text-[12px]">
<GlobeIcon className="size-3.5" />
Site
</a>
)}
{lead.maps_url && (
<a href={lead.maps_url} target="_blank" rel="noopener noreferrer nofollow" className="h-7 px-2 rounded-md border border-slate-200 text-slate-600 hover:text-slate-900 inline-flex items-center gap-1 text-[12px]">
<MapIcon className="size-3.5" />
Map
</a>
)}
</div>
</header>
<ScrollStrip activeKey={tab} className="shrink-0 border-b border-slate-200" innerClassName="px-3 flex items-center gap-1">
{(
[
["overview", "Overview", InfoIcon],
["people", "People", UsersIcon],
["website", "Website", GlobeIcon],
["notes", "Notes", FileTextIcon],
] as const
).map(([key, label, Icon]) => (
<button
key={key}
type="button"
data-active={tab === key || undefined}
onClick={() => onTab(key)}
className={cn("relative h-10 px-2.5 inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap text-[12.5px]", tab === key ? "text-slate-900 font-medium" : "text-slate-500 hover:text-slate-900")}
>
<Icon className="size-3.5" />
{label}
{key === "people" && lead.people_count > 0 && (
<span className="rounded-full bg-slate-100 px-1.5 text-[10.5px] font-medium tabular-nums text-slate-600">{lead.people_count}</span>
)}
{tab === key && <span className="absolute inset-x-2 -bottom-px h-0.5 rounded-full bg-sky-600" />}
</button>
))}
</ScrollStrip>
<div className="flex-1 min-h-0 overflow-y-auto px-4 py-3">
{tab === "overview" && <Overview lead={lead} provider={provider} onPeople={() => onTab("people")} />}
{tab === "people" && <PeopleTab lead={lead} onFindPeople={findEmails} finding={enrich.isPending || lead.enrichment_status === "queued"} />}
{tab === "website" && <Website lead={lead} />}
{tab === "notes" && <Notes key={lead.id} lead={lead} />}
</div>
</>
);
}
function Section({ title, children }: { title: string; children: React.ReactNode }) {
return (
<section className="mb-4">
<h3 className="mb-1.5 text-[10px] font-medium uppercase tracking-[0.14em] text-slate-400">{title}</h3>
{children}
</section>
);
}
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 && (
<Section title="Decision makers">
<button type="button" onClick={onPeople} className="w-full rounded-md border border-slate-200 px-2.5 py-2 text-left hover:border-slate-300">
{deciders.map((p) => (
<div key={p.id} className="flex items-center gap-2 py-0.5 text-[12px]">
<span className="truncate font-medium text-slate-800">{p.name}</span>
{p.title && <span className="truncate text-slate-500">{p.title}</span>}
{p.email && p.email_status !== "suppressed" && <MailIcon className="ml-auto size-3 shrink-0 text-emerald-600" aria-label="Has an address" />}
</div>
))}
<span className="mt-1 block text-[11px] text-sky-700">
{lead.people_count > deciders.length ? `See all ${lead.people_count} people` : "See people"}
</span>
</button>
</Section>
)}
<Section title="Emails">
{lead.emails.length === 0 ? (
<p className="text-[12px] text-slate-500">
{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."}
</p>
) : (
<ul className="space-y-1">
{lead.emails.map((e) => {
const v = emailVerdict(e);
return (
<li key={e.email} className="group flex items-center gap-2 rounded-md border border-slate-200 px-2 py-1.5">
<MailIcon className="size-3.5 shrink-0 text-slate-400" />
<div className="min-w-0 flex-1">
<div className="flex items-center gap-1.5">
<span className={cn("truncate text-[12.5px]", e.email === lead.email ? "font-medium text-slate-900" : "text-slate-700")}>{e.email}</span>
{e.email === lead.email && <span className="rounded bg-sky-50 px-1 text-[10px] text-sky-700">Primary</span>}
</div>
<div className="flex items-center gap-1.5 text-[10.5px] text-slate-400">
<span className={cn("inline-flex items-center gap-0.5", v.tone)}>
{v.icon}
{v.label}
</span>
<span>·</span>
<span>{e.source === "website" ? "From the website" : `From ${provider}`}</span>
{e.domain_match && <span>· On their domain</span>}
</div>
</div>
<button
type="button"
aria-label={`Copy ${e.email}`}
onClick={() => copy(e.email)}
className="size-6 rounded text-slate-400 hover:text-slate-800 hover:bg-slate-100 inline-flex items-center justify-center opacity-100 md:opacity-0 md:group-hover:opacity-100"
>
<CopyIcon className="size-3" />
</button>
</li>
);
})}
</ul>
)}
</Section>
<Section title="Details">
<dl className="space-y-1.5 text-[12px]">
{lead.phone && (
<Fact icon={<PhoneIcon className="size-3.5" />}>
<a href={`tel:${lead.phone}`} className="text-slate-800 hover:text-sky-700">
{lead.phone}
</a>
</Fact>
)}
{lead.website && (
<Fact icon={<GlobeIcon className="size-3.5" />}>
<a href={lead.website} target="_blank" rel="noopener noreferrer nofollow" className="inline-flex items-center gap-1 text-slate-800 hover:text-sky-700">
{lead.domain || lead.website}
<ExternalLinkIcon className="size-3" />
</a>
{lead.site.found_website && <span className="ml-1.5 text-[11px] text-slate-400">Found from the name, confirmed on the site</span>}
</Fact>
)}
{lead.address && (
<Fact icon={<MapPinIcon className="size-3.5" />}>
<span className="text-slate-800">{lead.address}</span>
</Fact>
)}
{(lead.rating != null || lead.review_count != null) && (
<Fact icon={<StarIcon className="size-3.5" />}>
<span className="text-slate-800">
{lead.rating != null ? `${lead.rating.toFixed(1)} stars` : "No rating"}
{lead.review_count != null && <span className="text-slate-500"> from {lead.review_count.toLocaleString()} reviews</span>}
{lead.price_level != null && <span className="text-slate-500"> · {"$".repeat(lead.price_level)}</span>}
</span>
</Fact>
)}
{lead.business_status && lead.business_status !== "operational" && (
<Fact icon={<InfoIcon className="size-3.5" />}>
<span className="text-rose-700">{lead.business_status === "closed" ? "Permanently closed" : "Temporarily closed"}</span>
</Fact>
)}
{lead.chain && (
<Fact icon={<BuildingIcon className="size-3.5" />}>
<span className="text-slate-800">Part of {lead.chain}</span>
</Fact>
)}
</dl>
{lead.description && <p className="mt-2 text-[12px] leading-relaxed text-slate-600">{lead.description}</p>}
</Section>
{socials.length > 0 && (
<Section title="Social profiles">
<div className="flex flex-wrap gap-1.5">
{socials.map(([kind, url]) => (
<a
key={kind}
href={url}
target="_blank"
rel="noopener noreferrer nofollow"
className="h-6 px-2 rounded-md border border-slate-200 text-[11.5px] text-slate-600 hover:text-slate-900 hover:border-slate-300 inline-flex items-center gap-1"
>
{SOCIAL_LABEL[kind] ?? kind}
<ExternalLinkIcon className="size-3" />
</a>
))}
</div>
</Section>
)}
{lead.hours.length > 0 && (
<Section title="Hours">
<ul className="space-y-0.5 text-[12px] text-slate-700">
{lead.hours.map((h) => (
<li key={h} className="flex items-center gap-1.5">
<ClockIcon className="size-3 text-slate-400" />
{h}
</li>
))}
</ul>
</Section>
)}
{lead.categories.length > 0 && (
<Section title="Categories">
<div className="flex flex-wrap gap-1">
{lead.categories.map((c) => (
<span key={c} className="rounded bg-slate-100 px-1.5 py-0.5 text-[11px] text-slate-600">
{c}
</span>
))}
</div>
</Section>
)}
<p className="text-[11px] text-slate-400">
From {provider} · first found {timeAgo(lead.first_seen_at)}
</p>
</>
);
}
function Fact({ icon, children }: { icon: React.ReactNode; children: React.ReactNode }) {
return (
<div className="flex items-start gap-2">
<span className="mt-0.5 text-slate-400">{icon}</span>
<div className="min-w-0 break-words">{children}</div>
</div>
);
}
function Website({ lead }: { lead: Lead }) {
const s = lead.site;
if (!lead.website)
return (
<p className="text-[12px] text-slate-500">
{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."}
</p>
);
if (!s.checked_at) return <p className="text-[12px] text-slate-500">Not read yet. Find people and emails reads the site and reports what it runs on.</p>;
if (!s.reachable) return <p className="text-[12px] text-rose-700">The website could not be read{s.error ? `: ${s.error}` : "."}</p>;
return (
<>
<Section title="Site">
<dl className="space-y-1.5 text-[12px]">
<Fact icon={s.https ? <LockIcon className="size-3.5 text-emerald-600" /> : <LockIcon className="size-3.5 text-rose-500" />}>
<span className="text-slate-800">{s.https ? "Served over HTTPS" : "No HTTPS"}</span>
</Fact>
{s.platform && (
<Fact icon={<GlobeIcon className="size-3.5" />}>
<span className="text-slate-800">Built with {s.platform}</span>
</Fact>
)}
<Fact icon={<FileTextIcon className="size-3.5" />}>
<span className="text-slate-800">
{s.pages ?? 1} page{(s.pages ?? 1) === 1 ? "" : "s"} read {timeAgo(s.checked_at)}
</span>
</Fact>
</dl>
{(s.title || s.description) && (
<div className="mt-2 rounded-md border border-slate-200 bg-slate-50/60 px-2.5 py-2">
{s.title && <p className="text-[12px] font-medium text-slate-800">{s.title}</p>}
{s.description && <p className="mt-0.5 text-[11.5px] leading-relaxed text-slate-600">{s.description}</p>}
</div>
)}
</Section>
{s.signals && s.signals.length > 0 && (
<Section title="Signals">
<div className="flex flex-wrap gap-1">
{s.signals.map((sig) => {
const gap = /^No |Not |Outdated/.test(sig);
return (
<span key={sig} className={cn("rounded px-1.5 py-0.5 text-[11px]", gap ? "bg-amber-50 text-amber-800" : "bg-emerald-50 text-emerald-800")}>
{sig}
</span>
);
})}
</div>
<p className="mt-1.5 text-[11px] text-slate-400">Amber marks a gap you could offer to fix.</p>
</Section>
)}
</>
);
}
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<typeof update.mutate>[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 (
<>
<Section title="Tags">
<div className="flex flex-wrap items-center gap-1">
{lead.tags.map((t) => (
<span key={t} className="h-6 pl-2 pr-1 rounded-md bg-sky-50 text-sky-700 text-[11.5px] inline-flex items-center gap-1">
<TagIcon className="size-3" />
{t}
<button type="button" aria-label={`Remove ${t}`} onClick={() => save({ tags: lead.tags.filter((x) => x !== t) })} className="size-4 rounded hover:bg-sky-100 inline-flex items-center justify-center">
<XIcon className="size-3" />
</button>
</span>
))}
<input
value={tag}
maxLength={40}
onChange={(e) => 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"
/>
</div>
</Section>
<Section title="Notes">
<textarea
value={notes}
maxLength={5000}
onChange={(e) => {
dirty.current = true;
setNotes(e.target.value);
}}
onBlur={() => {
dirty.current = false;
if (notes !== lead.notes) save({ notes });
}}
rows={8}
placeholder="What you know about them, who to ask for, when to follow up…"
className="w-full resize-y rounded-md border border-slate-200 px-2.5 py-2 text-[12.5px] text-slate-800 outline-none focus:border-sky-400 focus:ring-2 focus:ring-sky-100"
/>
<p className="mt-1 text-[11px] text-slate-400">Saved when you click away. Your team sees it too.</p>
</Section>
</>
);
}
@@ -0,0 +1,184 @@
import { AnimatePresence, motion } from "framer-motion";
import { CheckIcon, SearchIcon, SlidersHorizontalIcon, StarIcon, XIcon } from "lucide-react";
import { PopoverMenu, PopoverMenuContent, PopoverMenuTrigger } from "@/components/ui/popover-menu";
import ScrollStrip from "@/components/ui/scroll-strip";
import type { LeadFacets } from "@/lib/api/models/app/leads/Lead";
import { cn } from "@/lib/utils";
import FilterPanel from "./FilterPanel";
import { EMPTY_REFINE, refineChips, refineCount, type ReachFilter, type Refine } from "./refine";
// The filters people reach for most sit on the bar as one-tap toggles; the
// rest open from "Filters" and show up as chips once they are on.
const QUICK: { key: string; label: string; on: (r: Refine) => boolean; flip: (r: Refine) => Refine; icon?: "star" }[] = [
{ key: "reach:email", label: "Has email", on: (r) => r.reach.includes("email"), flip: (r) => flipReach(r, "email") },
{ key: "reach:website", label: "Has website", on: (r) => r.reach.includes("website"), flip: (r) => flipReach(r, "website") },
{ key: "reach:phone", label: "Has phone", on: (r) => r.reach.includes("phone"), flip: (r) => flipReach(r, "phone") },
{ key: "rating", label: "4+", icon: "star", on: (r) => r.minRating === 4, flip: (r) => ({ ...r, minRating: r.minRating === 4 ? null : 4 }) },
];
function flipReach(r: Refine, id: ReachFilter): Refine {
if (r.reach.includes(id)) return { ...r, reach: r.reach.filter((x) => x !== id) };
const reach = [...r.reach, id].filter((x) => !(id === "website" && x === "no_website"));
return { ...r, reach };
}
const spring = { type: "spring", stiffness: 520, damping: 34, mass: 0.6 } as const;
export default function LeadFilterBar({
text,
onText,
value,
onChange,
facets,
}: {
text: string;
onText: (v: string) => void;
value: Refine;
onChange: (r: Refine) => void;
facets?: LeadFacets;
}) {
// A chip is hidden only while its toggle shows it; a 3+ rating still gets one.
const quickKeys = new Set(QUICK.filter((q) => q.on(value)).map((q) => q.key));
const chips = refineChips(value).filter((c) => !quickKeys.has(c.key));
const count = refineCount(value);
const anything = count > 0 || text.trim() !== "";
return (
<div className="shrink-0 h-11 pl-3 pr-2 flex items-center gap-2 border-b border-slate-200 bg-white">
<div className="relative w-40 sm:w-56 shrink-0">
<SearchIcon className="absolute left-2 top-1/2 -translate-y-1/2 size-3.5 text-slate-400" />
<input
value={text}
onChange={(e) => onText(e.target.value)}
onKeyDown={(e) => e.key === "Escape" && onText("")}
placeholder="Filter by name, email, domain"
aria-label="Filter leads"
className="h-7 w-full rounded-md border border-slate-200 bg-white pl-7 pr-6 text-[12.5px] text-slate-900 placeholder:text-slate-400 outline-none transition-[border-color,box-shadow] focus:border-sky-400 focus:ring-2 focus:ring-sky-100"
/>
<AnimatePresence>
{text && (
<motion.button
type="button"
aria-label="Clear filter text"
onClick={() => onText("")}
initial={{ opacity: 0, scale: 0.6 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.6 }}
transition={{ duration: 0.12 }}
className="absolute right-1 top-1/2 -translate-y-1/2 size-5 rounded text-slate-400 hover:text-slate-700 inline-flex items-center justify-center"
>
<XIcon className="size-3" />
</motion.button>
)}
</AnimatePresence>
</div>
<ScrollStrip className="flex-1" innerClassName="gap-1.5 py-1">
{QUICK.map((q) => {
const on = q.on(value);
return (
<motion.button
key={q.key}
type="button"
aria-pressed={on}
whileTap={{ scale: 0.94 }}
onClick={() => onChange(q.flip(value))}
className={cn(
"h-7 shrink-0 px-2.5 rounded-full border text-[12px] inline-flex items-center gap-1 transition-colors duration-150",
on ? "border-sky-300 bg-sky-50 text-sky-700" : "border-slate-200 bg-white text-slate-600 hover:border-slate-300 hover:text-slate-900",
)}
>
<AnimatePresence initial={false}>
{on && (
<motion.span
initial={{ width: 0, opacity: 0 }}
animate={{ width: "auto", opacity: 1 }}
exit={{ width: 0, opacity: 0 }}
transition={{ duration: 0.16 }}
className="inline-flex overflow-hidden"
>
<CheckIcon className="size-3" />
</motion.span>
)}
</AnimatePresence>
{q.icon === "star" && <StarIcon className={cn("size-3", on ? "fill-amber-400 text-amber-400" : "text-slate-400")} />}
{q.label}
</motion.button>
);
})}
<AnimatePresence initial={false} mode="popLayout">
{chips.map((c) => (
<motion.span
key={c.key}
layout
initial={{ opacity: 0, scale: 0.85 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.85 }}
transition={spring}
className="h-7 shrink-0 pl-2.5 pr-1 rounded-full bg-slate-900 text-white text-[12px] inline-flex items-center gap-1"
>
{c.label}
<button
type="button"
aria-label={`Remove ${c.label}`}
onClick={() => onChange(c.clear(value))}
className="size-5 rounded-full text-white/60 hover:text-white hover:bg-white/15 inline-flex items-center justify-center"
>
<XIcon className="size-3" />
</button>
</motion.span>
))}
</AnimatePresence>
</ScrollStrip>
<AnimatePresence initial={false}>
{anything && (
<motion.button
type="button"
onClick={() => {
onChange(EMPTY_REFINE);
onText("");
}}
initial={{ opacity: 0, x: 6 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: 6 }}
transition={{ duration: 0.15 }}
className="hidden sm:inline-flex h-7 shrink-0 px-2 rounded-md text-[12px] text-slate-500 hover:text-slate-900 hover:bg-slate-100 items-center"
>
Clear
</motion.button>
)}
</AnimatePresence>
<PopoverMenu align="end">
<PopoverMenuTrigger asChild>
<button
type="button"
className="h-7 shrink-0 px-2.5 rounded-md border border-slate-200 bg-white text-[12px] font-medium text-slate-700 hover:border-slate-300 hover:text-slate-900 data-[state=open]:border-sky-300 data-[state=open]:bg-sky-50 data-[state=open]:text-sky-700 inline-flex items-center gap-1.5 transition-colors"
>
<SlidersHorizontalIcon className="size-3.5" />
<span className="hidden sm:inline">Filters</span>
<AnimatePresence initial={false}>
{count > 0 && (
<motion.span
key={count}
initial={{ scale: 0.5, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
exit={{ scale: 0.5, opacity: 0 }}
transition={spring}
className="min-w-4 rounded-full bg-sky-600 px-1 text-center text-[10px] leading-4 text-white tabular-nums"
>
{count}
</motion.span>
)}
</AnimatePresence>
</button>
</PopoverMenuTrigger>
<PopoverMenuContent role="dialog" aria-label="Filters" minWidth={340} className="w-[340px] p-3.5">
<FilterPanel value={value} onChange={onChange} facets={facets} />
</PopoverMenuContent>
</PopoverMenu>
</div>
);
}
+510
View File
@@ -0,0 +1,510 @@
import { useEffect, useRef, useState } from "react";
import maplibregl, { type ExpressionSpecification, type GeoJSONSource, type GeoJSONSourceSpecification, type Map as MapLibreMap, type MapMouseEvent, type MapTouchEvent } from "maplibre-gl";
import "maplibre-gl/dist/maplibre-gl.css";
import { MailIcon, GlobeIcon, PhoneIcon, StarIcon } from "lucide-react";
import type { LatLng, LeadArea, LeadBounds, LeadPoint } from "@/lib/api/models/app/leads/Lead";
import { applyMapTheme } from "./mapTheme";
import { areaRing, boundsOf, circleBounds, circleRing, distanceM } from "./geo";
type FeatureCollection = Extract<Exclude<GeoJSONSourceSpecification["data"], string>, { type: "FeatureCollection" }>;
export type MapTool = "pan" | "rect" | "circle" | "polygon" | "lasso";
export type ColorBy = "reach" | "status" | "score" | "rating";
export type MapLayerMode = "pins" | "heat";
export interface MapView {
center: LatLng;
zoom: number;
bounds: LeadBounds;
}
export interface MapControls {
zoomBy: (delta: number) => void;
}
export interface FlyTarget {
key: number;
center?: LatLng;
bounds?: LeadBounds;
zoom?: number;
}
interface Props {
styleUrl: string;
dark: boolean;
// themed lays Warmbly's palette over the style; off keeps the style's own colors.
themed: boolean;
controls?: React.RefObject<MapControls | null>;
points: LeadPoint[];
selected: Set<string>;
activeId: string | null;
colorBy: ColorBy;
layer: MapLayerMode;
area: LeadArea | null;
tool: MapTool;
tilt: boolean;
initialView: { center: LatLng; zoom: number };
fly: FlyTarget | null;
onToolDone: () => void;
onArea: (area: LeadArea) => void;
onLasso: (polygon: LatLng[]) => void;
onPick: (id: string, additive: boolean) => void;
onView: (view: MapView) => void;
}
// Pin colors per mode, as MapLibre expressions over each feature's properties.
const COLOR: Record<ColorBy, ExpressionSpecification> = {
reach: ["case", ["get", "has_email"], "#10b981", ["get", "has_website"], "#0ea5e9", ["get", "has_phone"], "#f59e0b", "#94a3b8"],
status: ["match", ["get", "status"], "saved", "#8b5cf6", "contacted", "#10b981", "dismissed", "#94a3b8", "#0ea5e9"],
score: ["interpolate", ["linear"], ["get", "score"], 0, "#cbd5e1", 35, "#7dd3fc", 70, "#0284c7", 100, "#0c4a6e"],
rating: ["case", ["<", ["get", "rating"], 0], "#94a3b8", [">=", ["get", "rating"], 4.5], "#059669", [">=", ["get", "rating"], 4], "#10b981", [">=", ["get", "rating"], 3], "#f59e0b", "#f43f5e"],
};
function toCollection(points: LeadPoint[], selected: Set<string>, activeId: string | null): FeatureCollection {
return {
type: "FeatureCollection",
features: points.map((p) => ({
type: "Feature",
id: p.id,
geometry: { type: "Point", coordinates: [p.longitude, p.latitude] },
properties: {
id: p.id,
status: p.status,
score: p.score,
rating: p.rating ?? -1,
has_email: p.has_email,
has_website: p.has_website,
has_phone: p.has_phone,
selected: selected.has(p.id),
active: p.id === activeId,
},
})),
};
}
function ringFeature(ring: [number, number][]): FeatureCollection {
if (ring.length < 2) return { type: "FeatureCollection", features: [] };
const closed = ring.length >= 3;
return {
type: "FeatureCollection",
features: [
closed
? { type: "Feature", properties: {}, geometry: { type: "Polygon", coordinates: [ring] } }
: { type: "Feature", properties: {}, geometry: { type: "LineString", coordinates: ring } },
],
};
}
const EMPTY: FeatureCollection = { type: "FeatureCollection", features: [] };
export default function LeadMap(props: Props) {
const container = useRef<HTMLDivElement>(null);
const mapRef = useRef<MapLibreMap | null>(null);
const latest = useRef(props);
latest.current = props;
const [ready, setReady] = useState(0);
const [hover, setHover] = useState<{ point: LeadPoint; x: number; y: number } | null>(null);
const byId = useRef(new Map<string, LeadPoint>());
byId.current = new Map(props.points.map((p) => [p.id, p]));
// One map per mount; style and data changes are applied to it in place.
useEffect(() => {
if (!container.current) return;
const map = new maplibregl.Map({
container: container.current,
style: latest.current.styleUrl,
center: [latest.current.initialView.center.lng, latest.current.initialView.center.lat],
zoom: latest.current.initialView.zoom,
attributionControl: { compact: true },
dragRotate: false,
pitchWithRotate: false,
maxPitch: 60,
});
mapRef.current = map;
if (latest.current.controls) latest.current.controls.current = { zoomBy: (d) => map.easeTo({ zoom: map.getZoom() + d, duration: 250 }) };
map.touchZoomRotate.disableRotation();
const install = () => {
const p = latest.current;
if (p.themed) applyMapTheme(map, p.dark);
if (!map.getSource("leads")) {
map.addSource("leads", { type: "geojson", data: EMPTY, cluster: true, clusterRadius: 46, clusterMaxZoom: 14, promoteId: "id" });
map.addSource("leads-flat", { type: "geojson", data: EMPTY });
map.addSource("area", { type: "geojson", data: EMPTY });
map.addSource("area-draft", { type: "geojson", data: EMPTY });
}
map.addLayer({
id: "area-fill",
type: "fill",
source: "area",
paint: { "fill-color": "#0ea5e9", "fill-opacity": 0.06 },
});
map.addLayer({
id: "area-line",
type: "line",
source: "area",
paint: { "line-color": "#0284c7", "line-width": 1.5, "line-dasharray": [2, 1.5] },
});
map.addLayer({
id: "area-draft-fill",
type: "fill",
source: "area-draft",
filter: ["==", ["geometry-type"], "Polygon"],
paint: { "fill-color": "#0ea5e9", "fill-opacity": 0.12 },
});
map.addLayer({
id: "area-draft-line",
type: "line",
source: "area-draft",
paint: { "line-color": "#0369a1", "line-width": 2 },
});
map.addLayer({
id: "leads-heat",
type: "heatmap",
source: "leads-flat",
layout: { visibility: "none" },
paint: {
"heatmap-weight": ["interpolate", ["linear"], ["get", "score"], 0, 0.2, 100, 1],
"heatmap-intensity": ["interpolate", ["linear"], ["zoom"], 8, 0.8, 15, 2],
"heatmap-radius": ["interpolate", ["linear"], ["zoom"], 8, 14, 15, 32],
"heatmap-opacity": 0.85,
"heatmap-color": [
"interpolate", ["linear"], ["heatmap-density"],
0, "rgba(14,165,233,0)", 0.2, "rgba(125,211,252,0.55)", 0.45, "#38bdf8", 0.7, "#0284c7", 1, "#f59e0b",
],
},
});
map.addLayer({
id: "leads-clusters",
type: "circle",
source: "leads",
filter: ["has", "point_count"],
paint: {
"circle-color": ["step", ["get", "point_count"], "#38bdf8", 25, "#0ea5e9", 100, "#0369a1"],
"circle-radius": ["step", ["get", "point_count"], 15, 25, 19, 100, 24],
"circle-stroke-width": 3,
"circle-stroke-color": p.dark ? "rgba(11,18,32,0.75)" : "rgba(255,255,255,0.85)",
},
});
map.addLayer({
id: "leads-cluster-count",
type: "symbol",
source: "leads",
filter: ["has", "point_count"],
layout: { "text-field": ["get", "point_count_abbreviated"], "text-size": 11, "text-font": ["Noto Sans Bold"], "text-allow-overlap": true },
paint: { "text-color": "#ffffff" },
});
map.addLayer({
id: "leads-halo",
type: "circle",
source: "leads",
filter: ["all", ["!", ["has", "point_count"]], ["any", ["get", "selected"], ["get", "active"]]],
paint: {
"circle-radius": ["case", ["get", "active"], 13, 10],
"circle-color": ["case", ["get", "active"], "rgba(14,165,233,0.28)", "rgba(14,165,233,0.18)"],
"circle-stroke-width": 1.5,
"circle-stroke-color": "#0284c7",
},
});
map.addLayer({
id: "leads-points",
type: "circle",
source: "leads",
filter: ["!", ["has", "point_count"]],
paint: {
"circle-color": COLOR[p.colorBy],
"circle-radius": ["interpolate", ["linear"], ["zoom"], 9, 4, 14, 6.5, 18, 8],
"circle-stroke-width": 2,
"circle-stroke-color": p.dark ? "#0b1220" : "#ffffff",
},
});
setReady((n) => n + 1);
};
map.on("style.load", install);
return () => {
map.remove();
mapRef.current = null;
};
}, []);
// Style switches drop every layer; style.load reinstalls them. Turning the palette off reloads to restore the style's own paint.
const firstStyle = useRef(true);
useEffect(() => {
if (firstStyle.current) {
firstStyle.current = false;
return;
}
mapRef.current?.setStyle(props.styleUrl);
}, [props.styleUrl, props.themed]);
useEffect(() => {
const map = mapRef.current;
if (!map || !ready) return;
if (props.themed) applyMapTheme(map, props.dark);
const stroke = props.dark ? "#0b1220" : "#ffffff";
if (map.getLayer("leads-points")) map.setPaintProperty("leads-points", "circle-stroke-color", stroke);
}, [props.dark, props.themed, ready]);
useEffect(() => {
const map = mapRef.current;
if (!map || !ready) return;
const data = toCollection(props.points, props.selected, props.activeId);
(map.getSource("leads") as GeoJSONSource | undefined)?.setData(data);
(map.getSource("leads-flat") as GeoJSONSource | undefined)?.setData(data);
}, [props.points, props.selected, props.activeId, ready]);
useEffect(() => {
const map = mapRef.current;
if (!map || !ready || !map.getLayer("leads-points")) return;
map.setPaintProperty("leads-points", "circle-color", COLOR[props.colorBy]);
}, [props.colorBy, ready]);
useEffect(() => {
const map = mapRef.current;
if (!map || !ready) return;
const heat = props.layer === "heat";
for (const id of ["leads-clusters", "leads-cluster-count", "leads-points", "leads-halo"]) {
if (map.getLayer(id)) map.setLayoutProperty(id, "visibility", heat ? "none" : "visible");
}
if (map.getLayer("leads-heat")) map.setLayoutProperty("leads-heat", "visibility", heat ? "visible" : "none");
}, [props.layer, ready]);
useEffect(() => {
const map = mapRef.current;
if (!map || !ready) return;
(map.getSource("area") as GeoJSONSource | undefined)?.setData(props.area ? ringFeature(areaRing(props.area)) : EMPTY);
}, [props.area, ready]);
useEffect(() => {
mapRef.current?.easeTo({ pitch: props.tilt ? 50 : 0, duration: 600 });
}, [props.tilt]);
useEffect(() => {
const map = mapRef.current;
const f = props.fly;
if (!map || !f) return;
if (f.bounds) {
map.fitBounds([[f.bounds.west, f.bounds.south], [f.bounds.east, f.bounds.north]], { padding: 64, maxZoom: 16, duration: 900 });
} else if (f.center) {
map.flyTo({ center: [f.center.lng, f.center.lat], zoom: f.zoom ?? Math.max(map.getZoom(), 14), duration: 900 });
}
}, [props.fly]);
// Clicks, hovers and the view report back through the latest props.
useEffect(() => {
const map = mapRef.current;
if (!map || !ready) return;
const report = () => {
const b = map.getBounds();
const c = map.getCenter();
latest.current.onView({
center: { lat: c.lat, lng: c.lng },
zoom: map.getZoom(),
bounds: { south: b.getSouth(), west: b.getWest(), north: b.getNorth(), east: b.getEast() },
});
};
report();
const onClusterClick = async (e: MapMouseEvent & { features?: maplibregl.MapGeoJSONFeature[] }) => {
const f = e.features?.[0];
if (!f || latest.current.tool !== "pan") return;
const src = map.getSource("leads") as GeoJSONSource;
const zoom = await src.getClusterExpansionZoom(f.properties.cluster_id as number);
const [lng, lat] = (f.geometry as unknown as { coordinates: [number, number] }).coordinates;
map.easeTo({ center: [lng, lat], zoom: zoom + 0.5 });
};
const onPointClick = (e: MapMouseEvent & { features?: maplibregl.MapGeoJSONFeature[] }) => {
const f = e.features?.[0];
if (!f || latest.current.tool !== "pan") return;
const ev = e.originalEvent as MouseEvent;
latest.current.onPick(String(f.properties.id), ev.shiftKey || ev.metaKey || ev.ctrlKey);
};
const onMove = (e: MapMouseEvent & { features?: maplibregl.MapGeoJSONFeature[] }) => {
const f = e.features?.[0];
const pt = f ? byId.current.get(String(f.properties.id)) : undefined;
if (pt && latest.current.tool === "pan") setHover({ point: pt, x: e.point.x, y: e.point.y });
};
const enter = () => {
if (latest.current.tool === "pan") map.getCanvas().style.cursor = "pointer";
};
const leave = () => {
if (latest.current.tool === "pan") map.getCanvas().style.cursor = "";
setHover(null);
};
map.on("moveend", report);
map.on("click", "leads-clusters", onClusterClick);
map.on("click", "leads-points", onPointClick);
map.on("mousemove", "leads-points", onMove);
map.on("mouseenter", "leads-points", enter);
map.on("mouseleave", "leads-points", leave);
map.on("mouseenter", "leads-clusters", enter);
map.on("mouseleave", "leads-clusters", leave);
map.on("movestart", () => setHover(null));
return () => {
map.off("moveend", report);
map.off("click", "leads-clusters", onClusterClick);
map.off("click", "leads-points", onPointClick);
map.off("mousemove", "leads-points", onMove);
map.off("mouseenter", "leads-points", enter);
map.off("mouseleave", "leads-points", leave);
map.off("mouseenter", "leads-clusters", enter);
map.off("mouseleave", "leads-clusters", leave);
};
}, [ready]);
// Drawing: rectangle and circle drag, polygon clicks, lasso freehand.
useEffect(() => {
const map = mapRef.current;
if (!map || !ready) return;
const tool = props.tool;
const draft = map.getSource("area-draft") as GeoJSONSource;
const clear = () => draft.setData(EMPTY);
if (tool === "pan") {
map.dragPan.enable();
map.doubleClickZoom.enable();
map.getCanvas().style.cursor = "";
clear();
return;
}
map.dragPan.disable();
map.doubleClickZoom.disable();
map.getCanvas().style.cursor = "crosshair";
setHover(null);
let start: maplibregl.LngLat | null = null;
let lassoPts: LatLng[] = [];
let poly: LatLng[] = [];
let lastPx: { x: number; y: number } | null = null;
const pos = (e: MapMouseEvent | MapTouchEvent) => e.lngLat;
const down = (e: MapMouseEvent | MapTouchEvent) => {
if (tool === "polygon") return;
e.preventDefault();
start = pos(e);
lassoPts = [{ lat: start.lat, lng: start.lng }];
lastPx = { x: e.point.x, y: e.point.y };
};
const move = (e: MapMouseEvent | MapTouchEvent) => {
const cur = pos(e);
if (tool === "polygon") {
if (poly.length) draft.setData(ringFeature([...poly, { lat: cur.lat, lng: cur.lng }].map((p) => [p.lng, p.lat] as [number, number])));
return;
}
if (!start) return;
if (tool === "rect") {
const b = boundsOf([{ lat: start.lat, lng: start.lng }, { lat: cur.lat, lng: cur.lng }]);
draft.setData(ringFeature([[b.west, b.south], [b.east, b.south], [b.east, b.north], [b.west, b.north], [b.west, b.south]]));
} else if (tool === "circle") {
const r = distanceM({ lat: start.lat, lng: start.lng }, { lat: cur.lat, lng: cur.lng });
draft.setData(ringFeature(circleRing({ lat: start.lat, lng: start.lng }, Math.max(r, 1))));
} else if (tool === "lasso" && lastPx && Math.hypot(e.point.x - lastPx.x, e.point.y - lastPx.y) > 6) {
lastPx = { x: e.point.x, y: e.point.y };
lassoPts.push({ lat: cur.lat, lng: cur.lng });
draft.setData(ringFeature([...lassoPts, lassoPts[0]].map((p) => [p.lng, p.lat] as [number, number])));
}
};
const up = (e: MapMouseEvent | MapTouchEvent) => {
if (tool === "polygon" || !start) return;
const cur = pos(e);
const s = { lat: start.lat, lng: start.lng };
const c = { lat: cur.lat, lng: cur.lng };
start = null;
clear();
const done = latest.current;
if (tool === "rect") {
const b = boundsOf([s, c]);
if (b.north - b.south > 1e-4 && b.east - b.west > 1e-4) done.onArea({ kind: "bbox", bounds: b });
} else if (tool === "circle") {
const r = Math.min(distanceM(s, c), 50000);
if (r >= 50) done.onArea({ kind: "circle", center: s, radius_m: Math.round(r), bounds: circleBounds(s, r) });
} else if (tool === "lasso" && lassoPts.length >= 3) {
done.onLasso(lassoPts);
}
done.onToolDone();
};
const click = (e: MapMouseEvent) => {
if (tool !== "polygon") return;
const p = { lat: e.lngLat.lat, lng: e.lngLat.lng };
if (poly.length >= 3) {
const first = map.project([poly[0].lng, poly[0].lat]);
if (Math.hypot(first.x - e.point.x, first.y - e.point.y) < 12) return finish();
}
poly.push(p);
draft.setData(ringFeature(poly.map((q) => [q.lng, q.lat] as [number, number])));
};
const finish = () => {
if (poly.length >= 3) latest.current.onArea({ kind: "polygon", polygon: poly, bounds: boundsOf(poly) });
poly = [];
clear();
latest.current.onToolDone();
};
const dbl = (e: MapMouseEvent) => {
if (tool !== "polygon") return;
e.preventDefault();
finish();
};
const key = (e: KeyboardEvent) => {
if (e.key === "Escape") {
poly = [];
start = null;
clear();
latest.current.onToolDone();
} else if (e.key === "Enter" && tool === "polygon") {
finish();
}
};
map.on("mousedown", down);
map.on("touchstart", down);
map.on("mousemove", move);
map.on("touchmove", move);
map.on("mouseup", up);
map.on("touchend", up);
map.on("click", click);
map.on("dblclick", dbl);
window.addEventListener("keydown", key);
return () => {
map.off("mousedown", down);
map.off("touchstart", down);
map.off("mousemove", move);
map.off("touchmove", move);
map.off("mouseup", up);
map.off("touchend", up);
map.off("click", click);
map.off("dblclick", dbl);
window.removeEventListener("keydown", key);
clear();
};
}, [props.tool, ready]);
return (
<div className="absolute inset-0">
{/* MapLibre makes its container position: relative, so size it explicitly. */}
<div ref={container} className="h-full w-full" />
{hover && <HoverCard point={hover.point} x={hover.x} y={hover.y} />}
</div>
);
}
function HoverCard({ point, x, y }: { point: LeadPoint; x: number; y: number }) {
return (
<div
className="pointer-events-none absolute z-10 w-[220px] rounded-lg border border-slate-200 bg-white/95 px-2.5 py-2 shadow-[0_8px_24px_-12px_rgba(15,23,42,0.35)] backdrop-blur"
style={{ left: x, top: y - 14, transform: "translate(-50%, -100%)" }}
>
<div className="truncate text-[12.5px] font-medium text-slate-900">{point.name}</div>
{point.category && <div className="truncate text-[11px] text-slate-500">{point.category}</div>}
<div className="mt-1.5 flex items-center gap-2 text-[11px] text-slate-500">
<MailIcon className={point.has_email ? "size-3 text-emerald-600" : "size-3 text-slate-300"} />
<GlobeIcon className={point.has_website ? "size-3 text-sky-600" : "size-3 text-slate-300"} />
<PhoneIcon className={point.has_phone ? "size-3 text-amber-600" : "size-3 text-slate-300"} />
{point.rating != null && (
<span className="inline-flex items-center gap-0.5">
<StarIcon className="size-3 fill-amber-400 text-amber-400" />
{point.rating.toFixed(1)}
{point.review_count != null && <span className="text-slate-400">({point.review_count})</span>}
</span>
)}
<span className="ml-auto tabular-nums text-slate-400">{point.score}</span>
</div>
</div>
);
}
@@ -0,0 +1,118 @@
import { AnimatePresence, motion } from "framer-motion";
import { BookmarkIcon, CheckIcon, DownloadIcon, Loader2Icon, MoreHorizontalIcon, SparklesIcon, TagIcon, Trash2Icon, UserPlusIcon, XIcon, EyeOffIcon, SendIcon } from "lucide-react";
import { useState } from "react";
import { PopoverMenu, PopoverMenuContent, PopoverMenuItem, PopoverMenuSeparator, PopoverMenuTrigger } from "@/components/ui/popover-menu";
import type { LeadStatus } from "@/lib/api/models/app/leads/Lead";
export default function LeadSelectionBar({
count,
enrichCost,
enriching,
onEnrich,
onAddToContacts,
onExport,
onStatus,
onTag,
onDelete,
onClear,
}: {
count: number;
enrichCost: number;
enriching: boolean;
onEnrich: () => void;
onAddToContacts: () => void;
onExport: () => void;
onStatus: (s: LeadStatus) => void;
onTag: (tag: string) => void;
onDelete: () => void;
onClear: () => void;
}) {
const [tag, setTag] = useState("");
return (
<AnimatePresence>
{count > 0 && (
<motion.div
initial={{ y: 16, opacity: 0 }}
animate={{ y: 0, opacity: 1 }}
exit={{ y: 16, opacity: 0 }}
transition={{ duration: 0.16 }}
className="fixed bottom-4 left-1/2 -translate-x-1/2 z-30 flex items-center max-w-[calc(100vw-16px)] flex-wrap justify-center md:max-w-none md:flex-nowrap gap-1.5 rounded-md border border-slate-200 bg-white shadow-[0_6px_20px_-4px_rgba(15,23,42,0.12),0_2px_4px_rgba(15,23,42,0.04)] px-2 py-1.5"
>
<div className="inline-flex items-center gap-1.5 px-2 h-7 rounded bg-sky-50 text-sky-700 text-[12px] font-medium">
<CheckIcon className="size-3" />
<span>{count.toLocaleString()} selected</span>
</div>
<Action onClick={onEnrich} disabled={enriching} title={enrichCost > 0 ? `${enrichCost} credit for each website read; unreachable sites are refunded` : undefined}>
{enriching ? <Loader2Icon className="size-3.5 animate-spin" /> : <SparklesIcon className="size-3.5" />}
Find people and emails
</Action>
<Action onClick={onAddToContacts}>
<UserPlusIcon className="size-3.5" />
Add to contacts
</Action>
<Action onClick={onExport}>
<DownloadIcon className="size-3.5" />
Export
</Action>
<PopoverMenu side="top" align="center" onOpenChange={(o) => !o && setTag("")}>
<PopoverMenuTrigger asChild>
<button type="button" aria-label="More actions" className="h-7 px-2 rounded-md text-slate-600 hover:text-slate-900 hover:bg-slate-100 inline-flex items-center">
<MoreHorizontalIcon className="size-3.5" />
</button>
</PopoverMenuTrigger>
<PopoverMenuContent minWidth={210}>
<PopoverMenuItem icon={<BookmarkIcon className="size-3.5" />} onSelect={() => onStatus("saved")}>
Mark as saved
</PopoverMenuItem>
<PopoverMenuItem icon={<SendIcon className="size-3.5" />} onSelect={() => onStatus("contacted")}>
Mark as contacted
</PopoverMenuItem>
<PopoverMenuItem icon={<EyeOffIcon className="size-3.5" />} onSelect={() => onStatus("dismissed")}>
Dismiss
</PopoverMenuItem>
<PopoverMenuSeparator />
<form
className="px-2 py-1.5 flex items-center gap-1.5"
onSubmit={(e) => {
e.preventDefault();
if (tag.trim()) onTag(tag.trim());
setTag("");
}}
>
<TagIcon className="size-3.5 text-slate-400" />
<input
value={tag}
maxLength={40}
onChange={(e) => setTag(e.target.value)}
placeholder="Add a tag, press Enter"
className="h-6 min-w-0 flex-1 rounded border border-slate-200 px-1.5 text-[12px] outline-none focus:border-sky-400"
/>
</form>
<PopoverMenuSeparator />
<PopoverMenuItem danger icon={<Trash2Icon className="size-3.5" />} onSelect={onDelete}>
Delete leads
</PopoverMenuItem>
</PopoverMenuContent>
</PopoverMenu>
<button type="button" aria-label="Clear selection" onClick={onClear} className="size-7 rounded-md text-slate-400 hover:text-slate-900 hover:bg-slate-100 inline-flex items-center justify-center">
<XIcon className="size-3.5" />
</button>
</motion.div>
)}
</AnimatePresence>
);
}
function Action({ onClick, disabled, title, children }: { onClick: () => void; disabled?: boolean; title?: string; children: React.ReactNode }) {
return (
<button
type="button"
onClick={onClick}
disabled={disabled}
title={title}
className="h-7 px-2.5 rounded-md text-[12px] font-medium text-slate-700 hover:text-slate-900 hover:bg-slate-100 inline-flex items-center gap-1.5 disabled:opacity-50"
>
{children}
</button>
);
}
+350
View File
@@ -0,0 +1,350 @@
import { useEffect, useRef, useState } from "react";
import { ArrowDownWideNarrowIcon, CheckIcon, GlobeIcon, Loader2Icon, MailXIcon, PhoneIcon, RotateCwIcon, SearchXIcon, SparklesIcon, StarIcon, UserCheckIcon, UsersIcon } from "lucide-react";
import { Checkbox } from "@/components/ui/checkbox";
import { PopoverMenu, PopoverMenuContent, PopoverMenuItem, PopoverMenuTrigger } from "@/components/ui/popover-menu";
import type { Lead, LeadSort } from "@/lib/api/models/app/leads/Lead";
import { cn } from "@/lib/utils";
import { EmailBadge, ScoreBar, StatusBadge } from "./badges";
const SORTS: { id: LeadSort; label: string }[] = [
{ id: "score", label: "Best leads first" },
{ id: "recent", label: "Most recently found" },
{ id: "rating", label: "Highest rated" },
{ id: "reviews", label: "Most reviewed" },
{ id: "name", label: "Name A to Z" },
];
export default function LeadsTable({
leads,
total,
loading,
error,
onRetry,
hasMore,
loadingMore,
onMore,
sort,
onSort,
selected,
allMatching,
onToggle,
onTogglePage,
onSelectAllMatching,
activeId,
onOpen,
onHover,
banner,
}: {
leads: Lead[];
total: number;
loading: boolean;
// Set when the list failed to load and there is nothing to show.
error?: string | null;
onRetry?: () => void;
hasMore: boolean;
loadingMore: boolean;
onMore: () => void;
sort: LeadSort;
onSort: (s: LeadSort) => void;
selected: Set<string>;
allMatching: boolean;
onToggle: (id: string, range: boolean) => void;
onTogglePage: (on: boolean) => void;
onSelectAllMatching: () => void;
activeId: string | null;
onOpen: (id: string) => void;
onHover: (id: string | null) => void;
// Search and website-run progress, shown above the rows.
banner?: React.ReactNode;
}) {
const sentinel = useRef<HTMLDivElement>(null);
useEffect(() => {
const el = sentinel.current;
if (!el || !hasMore) return;
const io = new IntersectionObserver((e) => e[0]?.isIntersecting && !loadingMore && onMore(), { rootMargin: "240px" });
io.observe(el);
return () => io.disconnect();
}, [hasMore, loadingMore, onMore]);
// Rows that just finished being read flash once as they turn over.
const wasQueued = useRef(new Set<string>());
const [justDone, setJustDone] = useState<Set<string>>(new Set());
useEffect(() => {
const done: string[] = [];
const queued = new Set<string>();
for (const l of leads) {
if (l.enrichment_status === "queued") queued.add(l.id);
else if (wasQueued.current.has(l.id)) done.push(l.id);
}
wasQueued.current = queued;
if (!done.length) return;
setJustDone((cur) => new Set([...cur, ...done]));
// Not cleared on re-render: a poll landing inside the flash would strand the highlight.
setTimeout(() => setJustDone((cur) => new Set([...cur].filter((id) => !done.includes(id)))), 2_400);
}, [leads]);
const pageAll = leads.length > 0 && leads.every((l) => selected.has(l.id));
const pageSome = leads.some((l) => selected.has(l.id));
return (
<div className="flex h-full min-h-0 flex-col">
<div className="shrink-0 h-9 px-3 flex items-center gap-2 border-b border-slate-200 bg-white">
<Checkbox
aria-label="Select every lead on screen"
checked={pageAll || allMatching}
ref={(el) => {
if (el) el.indeterminate = !pageAll && pageSome && !allMatching;
}}
onChange={(e) => onTogglePage(e.target.checked)}
/>
<span className="text-[12px] text-slate-500 tabular-nums">
{loading ? "Loading…" : `${total.toLocaleString()} lead${total === 1 ? "" : "s"}`}
</span>
{pageAll && !allMatching && total > leads.length && (
<button type="button" onClick={onSelectAllMatching} className="text-[11.5px] text-sky-700 hover:underline">
Select all {Math.min(total, 5000).toLocaleString()} matching
</button>
)}
<PopoverMenu align="end">
<PopoverMenuTrigger asChild>
<button
type="button"
className="ml-auto h-6 px-2 rounded-md text-[11.5px] text-slate-600 hover:text-slate-900 hover:bg-slate-100 inline-flex items-center gap-1.5"
>
<ArrowDownWideNarrowIcon className="size-3.5" />
{SORTS.find((s) => s.id === sort)?.label}
</button>
</PopoverMenuTrigger>
<PopoverMenuContent minWidth={190}>
{SORTS.map((s) => (
<PopoverMenuItem key={s.id} onSelect={() => onSort(s.id)} trailing={s.id === sort ? <CheckIcon className="size-3.5 text-sky-600" /> : undefined}>
{s.label}
</PopoverMenuItem>
))}
</PopoverMenuContent>
</PopoverMenu>
</div>
{banner}
{!loading && leads.length > 0 && (
<div className="shrink-0 h-7 pl-10 pr-3 flex items-center gap-3 border-b border-slate-100 bg-slate-50/60 text-[10px] font-medium uppercase tracking-[0.14em] text-slate-400">
<span className="flex-1">Business</span>
<span className="hidden lg:block w-[210px] shrink-0">Contact</span>
<span className="hidden xl:block w-[150px] shrink-0">Website</span>
<span className="hidden sm:block w-[64px] shrink-0">Rating</span>
<span className="w-[56px] shrink-0">Score</span>
<span className="hidden md:block w-[78px] shrink-0">Status</span>
</div>
)}
<div className="flex-1 min-h-0 overflow-y-auto">
{loading ? (
<div className="divide-y divide-slate-100">
{Array.from({ length: 8 }).map((_, i) => (
<div key={i} className="h-[58px] px-3 flex items-center gap-3">
<div className="size-4 rounded bg-slate-100" />
<div className="flex-1 space-y-1.5">
<div className="h-3 w-1/3 rounded bg-slate-100 animate-pulse" />
<div className="h-2.5 w-1/2 rounded bg-slate-100 animate-pulse" />
</div>
</div>
))}
</div>
) : error ? (
<div className="px-6 py-14 text-center">
<SearchXIcon className="mx-auto size-6 text-slate-300" />
<p className="mt-2 text-[12.5px] font-medium text-slate-900">Leads did not load</p>
<p className="mt-0.5 text-[11.5px] text-slate-400">{error}</p>
{onRetry && (
<button
type="button"
onClick={onRetry}
className="mt-3 h-7 px-3 rounded-md border border-slate-200 text-[12px] text-slate-700 hover:border-slate-300 hover:text-slate-900 inline-flex items-center gap-1.5"
>
<RotateCwIcon className="size-3.5" />
Try again
</button>
)}
</div>
) : leads.length === 0 ? (
<div className="px-6 py-14 text-center">
<SearchXIcon className="mx-auto size-6 text-slate-300" />
<p className="mt-2 text-[12.5px] font-medium text-slate-900">No leads here yet</p>
<p className="mt-0.5 text-[11.5px] text-slate-400">Search an area, or loosen the filters above.</p>
</div>
) : (
<ul className="divide-y divide-slate-100">
{leads.map((l) => (
<Row
key={l.id}
lead={l}
checked={allMatching || selected.has(l.id)}
active={l.id === activeId}
justDone={justDone.has(l.id)}
onToggle={(range) => onToggle(l.id, range)}
onOpen={() => onOpen(l.id)}
onHover={onHover}
/>
))}
</ul>
)}
<div ref={sentinel} />
{loadingMore && (
<div className="py-3 flex justify-center">
<Loader2Icon className="size-4 animate-spin text-slate-400" />
</div>
)}
</div>
</div>
);
}
function Row({
lead,
checked,
active,
justDone,
onToggle,
onOpen,
onHover,
}: {
lead: Lead;
checked: boolean;
active: boolean;
justDone: boolean;
onToggle: (range: boolean) => void;
onOpen: () => void;
onHover: (id: string | null) => void;
}) {
const working = lead.enrichment_status === "queued";
return (
<li
onClick={onOpen}
onMouseEnter={() => onHover(lead.id)}
onMouseLeave={() => onHover(null)}
data-active={active || undefined}
className={cn(
"group relative px-3 py-2 min-h-[52px] flex items-center gap-3 cursor-pointer transition-colors duration-700",
active ? "bg-sky-50/70" : justDone ? "bg-emerald-50/70" : working ? "bg-sky-50/30 hover:bg-sky-50/60" : "hover:bg-slate-50",
)}
>
{working && (
<>
<span aria-hidden className="absolute left-0 inset-y-0 w-0.5 bg-sky-500" />
<span aria-hidden className="absolute inset-x-0 bottom-0 h-px overflow-hidden">
<span className="absolute inset-y-0 w-1/3 bg-gradient-to-r from-transparent via-sky-400 to-transparent progress-sweep" />
</span>
</>
)}
<span onClick={(e) => e.stopPropagation()} className="shrink-0">
<Checkbox
aria-label={`Select ${lead.name}`}
checked={checked}
onChange={() => undefined}
onClick={(e) => onToggle((e as React.MouseEvent).shiftKey)}
/>
</span>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-1.5">
<span className="truncate text-[12.5px] font-medium text-slate-900">{lead.name}</span>
{lead.contact_id && (
<span title="Already a contact" className="shrink-0 text-emerald-600">
<UserCheckIcon className="size-3.5" />
</span>
)}
{lead.business_status === "closed" && <span className="shrink-0 rounded bg-rose-50 px-1 text-[10px] text-rose-700">Closed</span>}
{lead.people_count > 0 && (
<span title={`${lead.people_count} ${lead.people_count === 1 ? "person" : "people"} found`} className="shrink-0 inline-flex items-center gap-0.5 rounded bg-violet-50 px-1 text-[10px] font-medium tabular-nums text-violet-700">
<UsersIcon className="size-2.5" />
{lead.people_count}
</span>
)}
</div>
<div className="truncate text-[11.5px] text-slate-500">
{[lead.category, lead.city || lead.address].filter(Boolean).join(" · ")}
</div>
</div>
<div className="hidden lg:flex w-[210px] shrink-0 flex-col gap-0.5">
<ContactCell lead={lead} working={working} />
</div>
<div className="hidden xl:flex w-[150px] shrink-0 items-center gap-1 text-[11.5px] text-slate-600 min-w-0">
{lead.domain && (
<>
<GlobeIcon className="size-3 shrink-0 text-slate-400" />
<span className="truncate">{lead.domain}</span>
{lead.site.found_website && (
<span title="Not in the listing: worked out from the name and confirmed on the site" className="shrink-0 text-sky-600">
<SparklesIcon className="size-3" />
</span>
)}
</>
)}
</div>
<div className="hidden sm:flex w-[64px] shrink-0 items-center gap-1 text-[11.5px] text-slate-600 tabular-nums">
{lead.rating != null && (
<>
<StarIcon className="size-3 fill-amber-400 text-amber-400" />
{lead.rating.toFixed(1)}
{lead.review_count != null && <span className="text-slate-400">({compact(lead.review_count)})</span>}
</>
)}
</div>
<div className="w-[56px] shrink-0">
<ScoreBar score={lead.score} />
</div>
<div className="hidden md:block w-[78px] shrink-0">
<StatusBadge status={lead.status} />
</div>
</li>
);
}
// ContactCell says how to reach a lead, or what is happening to find out.
function ContactCell({ lead, working }: { lead: Lead; working: boolean }) {
const phone = lead.phone && (
<span className="inline-flex items-center gap-1 truncate text-[11.5px] text-slate-600 tabular-nums">
<PhoneIcon className="size-3 shrink-0 text-slate-400" />
{lead.phone}
</span>
);
if (working) {
return (
<>
<span className="inline-flex items-center gap-1.5 text-[11.5px]">
<span className="campaign-grid text-sky-600 shrink-0" aria-hidden />
<span className="text-shimmer font-medium text-sky-700">{lead.website ? "Reading the website" : "Looking for a website"}</span>
</span>
{phone}
</>
);
}
if (lead.email) {
return (
<>
<EmailBadge lead={lead} />
{phone}
</>
);
}
const note =
lead.enrichment_status === "done"
? "No email on the site"
: lead.enrichment_status === "no_website"
? "No website found"
: lead.enrichment_status === "failed"
? "Site did not answer"
: null;
return (
<>
{phone}
{note && (
<span className="inline-flex items-center gap-1 text-[11px] text-slate-400">
<MailXIcon className="size-3 shrink-0" />
{note}
</span>
)}
</>
);
}
function compact(n: number): string {
return n >= 1000 ? `${(n / 1000).toFixed(n >= 10000 ? 0 : 1)}k` : String(n);
}
@@ -0,0 +1,142 @@
import { useEffect, useRef, useState } from "react";
import { AnimatePresence, motion } from "framer-motion";
import { Loader2Icon, MapPinIcon, NavigationIcon, XIcon } from "lucide-react";
import useClickOutside from "@/hooks/useClickOutside";
import { geocodeLocation } from "@/lib/api/client/app/leads/leads";
import type { GeocodeResult, LatLng } from "@/lib/api/models/app/leads/Lead";
import { cn } from "@/lib/utils";
// A typed place that moves the map; suggestions come from the instance's geocoder.
export default function LocationSearch({
value,
onChange,
near,
onPick,
}: {
value: string;
onChange: (v: string) => void;
near: LatLng | null;
onPick: (r: GeocodeResult) => void;
}) {
const [open, setOpen] = useState(false);
const [results, setResults] = useState<GeocodeResult[]>([]);
const [loading, setLoading] = useState(false);
const [active, setActive] = useState(0);
const box = useRef<HTMLDivElement>(null);
const typed = useRef(false);
useClickOutside(open, () => setOpen(false), box);
useEffect(() => {
if (!typed.current) return;
const q = value.trim();
if (q.length < 2) {
setResults([]);
return;
}
const ctrl = new AbortController();
setLoading(true);
const t = window.setTimeout(() => {
geocodeLocation(q, near ?? undefined, ctrl.signal)
.then((r) => {
setResults(r);
setActive(0);
setOpen(true);
})
.catch(() => setResults([]))
.finally(() => setLoading(false));
}, 280);
return () => {
ctrl.abort();
window.clearTimeout(t);
};
// near only biases the ranking; a pan must not refire the lookup.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [value]);
const pick = (r: GeocodeResult) => {
typed.current = false;
onChange(r.detail ? `${r.label}, ${r.detail.split(", ")[0]}` : r.label);
onPick(r);
setOpen(false);
};
return (
<div ref={box} className="relative">
<div className="relative">
<MapPinIcon className="absolute left-2 top-1/2 -translate-y-1/2 size-3.5 text-slate-400" />
<input
value={value}
onChange={(e) => {
typed.current = true;
onChange(e.target.value);
}}
onFocus={() => results.length && setOpen(true)}
onKeyDown={(e) => {
if (!open || !results.length) return;
if (e.key === "ArrowDown") {
e.preventDefault();
setActive((a) => Math.min(a + 1, results.length - 1));
} else if (e.key === "ArrowUp") {
e.preventDefault();
setActive((a) => Math.max(a - 1, 0));
} else if (e.key === "Enter") {
e.preventDefault();
pick(results[active]);
}
}}
placeholder="City, neighborhood or address"
aria-label="Location"
className="h-8 w-full rounded-md border border-slate-200 bg-white pl-7 pr-7 text-[12.5px] text-slate-900 placeholder:text-slate-400 outline-none focus:border-sky-400 focus:ring-2 focus:ring-sky-100"
/>
{loading ? (
<Loader2Icon className="absolute right-2 top-1/2 -translate-y-1/2 size-3.5 animate-spin text-slate-400" />
) : value ? (
<button
type="button"
aria-label="Clear location"
onClick={() => {
onChange("");
setResults([]);
}}
className="absolute right-1.5 top-1/2 -translate-y-1/2 size-5 rounded text-slate-400 hover:text-slate-700 inline-flex items-center justify-center"
>
<XIcon className="size-3" />
</button>
) : null}
</div>
<AnimatePresence>
{open && results.length > 0 && (
<motion.ul
data-floating
initial={{ opacity: 0, y: -4 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -4 }}
transition={{ duration: 0.12 }}
className="absolute z-30 mt-1 w-full overflow-hidden rounded-md border border-slate-200 bg-white py-1 shadow-[0_12px_32px_-12px_rgba(15,23,42,0.3)]"
role="listbox"
>
{results.map((r, i) => (
<li key={`${r.label}-${r.center.lat}-${r.center.lng}`}>
<button
type="button"
role="option"
aria-selected={i === active}
onMouseEnter={() => setActive(i)}
onClick={() => pick(r)}
className={cn("w-full px-2.5 py-1.5 text-left flex items-start gap-2", i === active ? "bg-sky-50" : "hover:bg-slate-50")}
>
<NavigationIcon className="mt-0.5 size-3 shrink-0 text-slate-400" />
<span className="min-w-0">
<span className="block truncate text-[12.5px] text-slate-900">{r.label}</span>
{r.detail && <span className="block truncate text-[11px] text-slate-500">{r.detail}</span>}
</span>
{r.kind && <span className="ml-auto shrink-0 text-[10px] uppercase tracking-wide text-slate-400">{r.kind}</span>}
</button>
</li>
))}
</motion.ul>
)}
</AnimatePresence>
</div>
);
}
+386
View File
@@ -0,0 +1,386 @@
import { useState } from "react";
import toast from "react-hot-toast/headless";
import {
CopyIcon,
ExternalLinkIcon,
Loader2Icon,
MoreHorizontalIcon,
PencilIcon,
RefreshCwIcon,
SearchIcon,
Trash2Icon,
UserPlusIcon,
UsersIcon,
} from "lucide-react";
import { TextInput } from "@/components/ui/field";
import { PopoverMenu, PopoverMenuContent, PopoverMenuItem, PopoverMenuSeparator, PopoverMenuTrigger } from "@/components/ui/popover-menu";
import { useConfirm } from "@/hooks/context/confirm";
import type { AppError } from "@/lib/api/client/normalizeError";
import { useAddLeadPerson, useDeleteLeadPerson, useFindLeadPersonEmail, useUpdateLeadPerson } from "@/lib/api/hooks/app/leads/useLeads";
import type { Lead, LeadPerson, LeadPersonSource, LeadSeniority } from "@/lib/api/models/app/leads/Lead";
import buildError from "@/lib/helper/buildError";
import { cn } from "@/lib/utils";
import { personVerdict } from "./verdict";
const SENIORITY: Record<LeadSeniority, { label: string; tone: string; avatar: string }> = {
owner: { label: "Owner", tone: "bg-violet-50 text-violet-700", avatar: "bg-violet-100 text-violet-700" },
executive: { label: "Executive", tone: "bg-sky-50 text-sky-700", avatar: "bg-sky-100 text-sky-700" },
manager: { label: "Manager", tone: "bg-teal-50 text-teal-700", avatar: "bg-teal-100 text-teal-700" },
staff: { label: "", tone: "", avatar: "bg-slate-100 text-slate-600" },
};
const SOURCE: Record<LeadPersonSource, string> = {
schema: "Listed on the website",
page: "From the website",
imprint: "From the legal notice",
email: "From an address on the website",
linkedin: "Linked from the website",
manual: "Added by your team",
};
function initials(p: LeadPerson) {
const a = (p.first_name || p.name).charAt(0);
const b = p.last_name.charAt(0);
return (a + b).toUpperCase();
}
function copy(v: string) {
navigator.clipboard?.writeText(v).then(
() => toast.success("Copied"),
() => toast.error("Could not copy"),
);
}
export default function PeopleTab({ lead, onFindPeople, finding }: { lead: Lead; onFindPeople: () => void; finding: boolean }) {
const people = lead.people ?? [];
const pattern = lead.site.email_pattern;
const domain = lead.domain;
return (
<>
{people.length === 0 ? (
<div className="rounded-lg border border-dashed border-slate-200 px-4 py-5 text-center">
<div className="mx-auto mb-2 size-8 rounded-full bg-slate-50 text-slate-400 flex items-center justify-center">
<UsersIcon className="size-4" />
</div>
<p className="text-[12.5px] font-medium text-slate-800">
{lead.enrichment_status === "done" ? "The website names nobody who works here" : "Find the people who run this business"}
</p>
<p className="mx-auto mt-1 max-w-[280px] text-[11.5px] leading-relaxed text-slate-500">
{lead.enrichment_status === "done"
? "Add someone you know of below and their address is worked out from the domain."
: "Reading the website also goes through its team, about and legal pages for owners, managers and staff, then works out and checks their addresses."}
</p>
{lead.website && lead.enrichment_status !== "done" && (
<button
type="button"
onClick={onFindPeople}
disabled={finding}
className="mt-3 h-7 px-2.5 rounded-md bg-sky-600 text-white text-[12px] font-medium inline-flex items-center gap-1.5 hover:bg-sky-700 disabled:opacity-60"
>
{finding ? <Loader2Icon className="size-3.5 animate-spin" /> : <SearchIcon className="size-3.5" />}
{finding ? "Reading website…" : "Find people"}
</button>
)}
</div>
) : (
<>
{(pattern || lead.site.accepts_all) && domain && (
<div className="mb-3 rounded-md border border-slate-200 bg-slate-50/60 px-2.5 py-2 text-[11.5px] leading-relaxed text-slate-600">
{pattern && (
<p>
Addresses here look like <span className="font-mono text-[11px] text-slate-800">{patternExample(pattern)}@{domain}</span>
</p>
)}
{lead.site.accepts_all && (
<p className={cn(pattern && "mt-0.5")}>Their mail server accepts any address, so worked-out ones cannot be confirmed.</p>
)}
</div>
)}
<ul className="space-y-1.5">
{people.map((p) => (
<PersonRow key={p.id} lead={lead} person={p} />
))}
</ul>
</>
)}
<AddPerson lead={lead} />
</>
);
}
const PATTERN_EXAMPLE: Record<string, string> = {
"first.last": "jane.doe",
first: "jane",
flast: "jdoe",
firstlast: "janedoe",
"f.last": "j.doe",
last: "doe",
first_last: "jane_doe",
"first-last": "jane-doe",
"last.first": "doe.jane",
lastf: "doej",
firstl: "janed",
"first.l": "jane.d",
};
function patternExample(pattern: string) {
return PATTERN_EXAMPLE[pattern] ?? pattern;
}
function PersonRow({ lead, person: p }: { lead: Lead; person: LeadPerson }) {
const confirm = useConfirm();
const find = useFindLeadPersonEmail();
const remove = useDeleteLeadPerson();
const [editing, setEditing] = useState(false);
const seniority = SENIORITY[p.seniority];
const v = personVerdict(p);
const usable = p.email && p.email_status !== "suppressed" && p.email_status !== "invalid";
const findAgain = async () => {
try {
const out = await find.mutateAsync({ leadId: lead.id, personId: p.id });
toast.success(out.email ? `${out.email} · ${personVerdict(out).label}` : `No address found for ${out.name}`);
} catch (e) {
toast.error(buildError(e as unknown as AppError));
}
};
if (editing) return <PersonEditor lead={lead} person={p} onDone={() => setEditing(false)} />;
return (
<li className="group rounded-md border border-slate-200 px-2.5 py-2">
<div className="flex items-start gap-2.5">
<div className={cn("mt-0.5 size-7 shrink-0 rounded-full text-[11px] font-semibold flex items-center justify-center", seniority.avatar)}>{initials(p)}</div>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-1.5">
<span className="truncate text-[12.5px] font-medium text-slate-900">{p.name}</span>
{seniority.label && <span className={cn("shrink-0 rounded px-1 text-[10px]", seniority.tone)}>{seniority.label}</span>}
{p.contact_id && <span className="shrink-0 rounded bg-emerald-50 px-1 text-[10px] text-emerald-700">In contacts</span>}
</div>
{p.title && <p className="truncate text-[11.5px] text-slate-500">{p.title}</p>}
{p.email ? (
<div className="mt-1 flex items-center gap-1.5">
<span className={cn("truncate text-[12px]", usable ? "text-slate-800" : "text-slate-400 line-through")}>{p.email}</span>
<button
type="button"
aria-label={`Copy ${p.email}`}
onClick={() => copy(p.email)}
className="size-5 shrink-0 rounded text-slate-400 hover:text-slate-800 hover:bg-slate-100 inline-flex items-center justify-center opacity-100 md:opacity-0 md:group-hover:opacity-100"
>
<CopyIcon className="size-3" />
</button>
</div>
) : (
<p className="mt-1 text-[11.5px] text-slate-400">{find.isPending ? "Working out their address…" : "No address yet"}</p>
)}
<div className="mt-0.5 flex flex-wrap items-center gap-x-1.5 text-[10.5px] text-slate-400">
{p.email && (
<>
<span className={cn("inline-flex items-center gap-0.5", v.tone)} title={v.hint}>
{v.icon}
{v.label}
{p.email_confidence > 0 && p.email_status !== "suppressed" && <span className="text-slate-400"> · {p.email_confidence}%</span>}
</span>
<span>·</span>
</>
)}
{p.source_url ? (
<a href={p.source_url} target="_blank" rel="noopener noreferrer nofollow" className="hover:text-slate-700">
{SOURCE[p.source]}
</a>
) : (
<span>{SOURCE[p.source]}</span>
)}
</div>
</div>
<div className="flex shrink-0 items-center gap-0.5">
{p.linkedin_url && (
<a
href={p.linkedin_url}
target="_blank"
rel="noopener noreferrer nofollow"
aria-label={`${p.name} on LinkedIn`}
className="h-6 px-1.5 rounded text-[10.5px] font-semibold text-[#0A66C2] hover:bg-sky-50 inline-flex items-center gap-0.5"
>
in
<ExternalLinkIcon className="size-2.5" />
</a>
)}
<PopoverMenu align="end">
<PopoverMenuTrigger asChild>
<button
type="button"
aria-label={`More for ${p.name}`}
className="size-6 rounded text-slate-400 hover:text-slate-800 hover:bg-slate-100 inline-flex items-center justify-center"
>
{find.isPending ? <Loader2Icon className="size-3.5 animate-spin" /> : <MoreHorizontalIcon className="size-3.5" />}
</button>
</PopoverMenuTrigger>
<PopoverMenuContent minWidth={190}>
<PopoverMenuItem icon={<RefreshCwIcon className="size-3.5" />} onSelect={findAgain} disabled={find.isPending || !lead.domain}>
{p.email_source === "pattern" || !p.email ? "Find their email again" : "Check the address again"}
</PopoverMenuItem>
<PopoverMenuItem icon={<PencilIcon className="size-3.5" />} onSelect={() => setEditing(true)}>
Edit
</PopoverMenuItem>
<PopoverMenuSeparator />
<PopoverMenuItem
danger
icon={<Trash2Icon className="size-3.5" />}
onSelect={() =>
confirm.show(`Remove ${p.name} from ${lead.name}? A contact made from them stays.`, async () => {
try {
await remove.mutateAsync({ leadId: lead.id, personId: p.id });
} catch (e) {
toast.error(buildError(e as unknown as AppError));
}
})
}
>
Remove
</PopoverMenuItem>
</PopoverMenuContent>
</PopoverMenu>
</div>
</div>
</li>
);
}
function Field({ label, children }: { label: string; children: React.ReactNode }) {
return (
<label className="block min-w-0">
<span className="mb-0.5 block text-[10.5px] text-slate-500">{label}</span>
{children}
</label>
);
}
function PersonEditor({ lead, person, onDone }: { lead: Lead; person: LeadPerson; onDone: () => void }) {
const update = useUpdateLeadPerson();
const [first, setFirst] = useState(person.first_name);
const [last, setLast] = useState(person.last_name);
const [title, setTitle] = useState(person.title);
const [email, setEmail] = useState(person.email);
const [linkedin, setLinkedin] = useState(person.linkedin_url);
const save = async () => {
const patch: Record<string, string> = {};
if (first !== person.first_name) patch.first_name = first;
if (last !== person.last_name) patch.last_name = last;
if (title !== person.title) patch.title = title;
if (email.trim() !== person.email) patch.email = email;
if (linkedin !== person.linkedin_url) patch.linkedin_url = linkedin;
if (Object.keys(patch).length === 0) return onDone();
try {
await update.mutateAsync({ leadId: lead.id, personId: person.id, patch });
onDone();
} catch (e) {
toast.error(buildError(e as unknown as AppError));
}
};
return (
<li className="rounded-md border border-sky-200 bg-sky-50/30 px-2.5 py-2.5">
<div className="grid grid-cols-2 gap-2">
<Field label="First name">
<TextInput value={first} onChange={setFirst} maxLength={60} autoFocus />
</Field>
<Field label="Last name">
<TextInput value={last} onChange={setLast} maxLength={60} />
</Field>
<div className="col-span-2">
<Field label="Title">
<TextInput value={title} onChange={setTitle} maxLength={120} placeholder="Owner, office manager…" />
</Field>
</div>
<div className="col-span-2">
<Field label="Email">
<TextInput value={email} onChange={setEmail} type="email" maxLength={254} placeholder="Leave empty to work it out" />
</Field>
</div>
<div className="col-span-2">
<Field label="LinkedIn">
<TextInput value={linkedin} onChange={setLinkedin} maxLength={300} placeholder="https://www.linkedin.com/in/…" />
</Field>
</div>
</div>
<div className="mt-2.5 flex items-center justify-end gap-1.5">
<button type="button" onClick={onDone} className="h-7 px-2.5 rounded-md text-[12px] text-slate-600 hover:text-slate-900">
Cancel
</button>
<button
type="button"
onClick={save}
disabled={update.isPending || !first.trim()}
className="h-7 px-2.5 rounded-md bg-sky-600 text-white text-[12px] font-medium inline-flex items-center gap-1.5 hover:bg-sky-700 disabled:opacity-60"
>
{update.isPending && <Loader2Icon className="size-3.5 animate-spin" />}
Save
</button>
</div>
</li>
);
}
function AddPerson({ lead }: { lead: Lead }) {
const add = useAddLeadPerson();
const [first, setFirst] = useState("");
const [last, setLast] = useState("");
const [title, setTitle] = useState("");
const [email, setEmail] = useState("");
const ready = first.trim() !== "" && (last.trim() !== "" || email.trim() !== "") && (!!lead.domain || email.trim() !== "");
const submit = async () => {
if (!ready || add.isPending) return;
try {
const p = await add.mutateAsync({ leadId: lead.id, input: { first_name: first, last_name: last, title, email } });
setFirst("");
setLast("");
setTitle("");
setEmail("");
toast.success(p.email ? `${p.email} · ${personVerdict(p).label}` : `Added ${p.name}; no address could be worked out`);
} catch (e) {
toast.error(buildError(e as unknown as AppError));
}
};
const onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Enter") {
e.preventDefault();
submit();
}
};
return (
<section className="mt-4">
<h3 className="mb-1 text-[10px] font-medium uppercase tracking-[0.14em] text-slate-400">Find someone's email</h3>
<p className="mb-2 text-[11.5px] leading-relaxed text-slate-500">
{lead.domain
? `Know who you want? Their address at ${lead.domain} is worked out from their name and checked with the mail server.`
: "This business lists no website, so there is no domain to work an address out at. You can still add someone whose address you know."}
</p>
<div className="grid grid-cols-2 gap-2">
<Field label="First name">
<TextInput value={first} onChange={setFirst} maxLength={60} placeholder="Jane" onKeyDown={onKeyDown} />
</Field>
<Field label="Last name">
<TextInput value={last} onChange={setLast} maxLength={60} placeholder="Doe" onKeyDown={onKeyDown} />
</Field>
<Field label="Title (optional)">
<TextInput value={title} onChange={setTitle} maxLength={120} placeholder="Owner" onKeyDown={onKeyDown} />
</Field>
<Field label={lead.domain ? "Email, if you know it" : "Email"}>
<TextInput value={email} onChange={setEmail} type="email" maxLength={254} placeholder={lead.domain ? "Worked out if empty" : "jane@…"} onKeyDown={onKeyDown} />
</Field>
</div>
<div className="mt-2 flex items-center justify-between gap-2">
<p className="text-[11px] text-slate-400">{!ready && first.trim() ? (lead.domain ? "Add a last name to work out the address" : "Add their email address") : ""}</p>
<button
type="button"
onClick={submit}
disabled={!ready || add.isPending}
className="h-7 shrink-0 px-2.5 rounded-md bg-sky-600 text-white text-[12px] font-medium inline-flex items-center gap-1.5 hover:bg-sky-700 disabled:opacity-50"
>
{add.isPending ? <Loader2Icon className="size-3.5 animate-spin" /> : email.trim() || !lead.domain ? <UserPlusIcon className="size-3.5" /> : <SearchIcon className="size-3.5" />}
{add.isPending ? "Checking…" : email.trim() || !lead.domain ? "Add person" : "Find email"}
</button>
</div>
</section>
);
}
@@ -0,0 +1,229 @@
import { useState } from "react";
import { AnimatePresence, LayoutGroup, motion } from "framer-motion";
import toast from "react-hot-toast/headless";
import { BookmarkIcon, ChevronDownIcon, HistoryIcon, MoreHorizontalIcon, PencilIcon, Trash2Icon } from "lucide-react";
import { PopoverMenu, PopoverMenuContent, PopoverMenuItem, PopoverMenuSeparator, PopoverMenuTrigger } from "@/components/ui/popover-menu";
import { useConfirm } from "@/hooks/context/confirm";
import type { AppError } from "@/lib/api/client/normalizeError";
import { useDeleteLeadSearch, useLeadSearches, useUpdateLeadSearch } from "@/lib/api/hooks/app/leads/useLeads";
import type { LeadFinderConfig, LeadSearch } from "@/lib/api/models/app/leads/Lead";
import buildError from "@/lib/helper/buildError";
import timeAgo from "@/lib/helper/timeAgo";
import { cn } from "@/lib/utils";
export default function SavedSearches({
config,
activeId,
onOpen,
onDelete,
}: {
config: LeadFinderConfig;
activeId: string | null;
onOpen: (s: LeadSearch) => void;
onDelete: (id: string) => void;
}) {
const searches = useLeadSearches();
const list = searches.data ?? [];
const saved = list.filter((s) => s.saved);
const recent = list.filter((s) => !s.saved);
if (searches.isPending) {
return (
<div className="space-y-1.5">
{[0, 1, 2].map((i) => (
<div key={i} className="h-12 rounded-md bg-slate-100 animate-pulse" />
))}
</div>
);
}
if (!list.length) {
return (
<div className="flex items-start gap-2.5 rounded-lg border border-dashed border-slate-200 px-3 py-3">
<HistoryIcon className="mt-0.5 size-4 shrink-0 text-slate-300" />
<p className="text-[11.5px] leading-relaxed text-slate-500">
Your searches show up here, so you can open one again later. Bookmark the ones you come back to.
</p>
</div>
);
}
// One layout group, so a bookmarked search glides from Recent up into Saved.
return (
<LayoutGroup>
<div className="space-y-4">
<AnimatePresence initial={false}>
{saved.length > 0 && <Section key="saved" title="Saved" items={saved} config={config} activeId={activeId} onOpen={onOpen} onDelete={onDelete} />}
</AnimatePresence>
{recent.length > 0 && <Section title="Recent" items={recent} config={config} activeId={activeId} onOpen={onOpen} onDelete={onDelete} cap={4} />}
</div>
</LayoutGroup>
);
}
function Section({
title,
items,
config,
activeId,
onOpen,
onDelete,
cap,
}: {
title: string;
items: LeadSearch[];
config: LeadFinderConfig;
activeId: string | null;
onOpen: (s: LeadSearch) => void;
onDelete: (id: string) => void;
/** Show this many until the list is opened up. */
cap?: number;
}) {
const [all, setAll] = useState(false);
const hidden = cap && !all ? Math.max(items.length - cap, 0) : 0;
const shown = hidden ? items.slice(0, cap) : items;
return (
<motion.div layout initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} transition={{ duration: 0.18 }}>
<motion.div layout="position" className="mb-1.5 flex items-center text-[10px] font-medium uppercase tracking-[0.14em] text-slate-400">
{title}
<span className="ml-1.5 tabular-nums text-slate-300">{items.length}</span>
</motion.div>
<ul className="space-y-1">
<AnimatePresence initial={false}>
{shown.map((s) => (
<SearchRow key={s.id} search={s} config={config} active={s.id === activeId} onOpen={() => onOpen(s)} onDelete={() => onDelete(s.id)} />
))}
</AnimatePresence>
</ul>
{cap && items.length > cap && (
<motion.button
layout="position"
type="button"
onClick={() => setAll((v) => !v)}
className="mt-1.5 inline-flex h-6 items-center gap-1 rounded-md px-1.5 text-[11.5px] text-slate-500 hover:bg-slate-100 hover:text-slate-900"
>
{all ? "Show fewer" : `Show ${hidden} more`}
<ChevronDownIcon className={cn("size-3 transition-transform duration-200", all && "rotate-180")} />
</motion.button>
)}
</motion.div>
);
}
function SearchRow({ search, config, active, onOpen, onDelete }: { search: LeadSearch; config: LeadFinderConfig; active: boolean; onOpen: () => void; onDelete: () => void }) {
const update = useUpdateLeadSearch();
const remove = useDeleteLeadSearch();
const confirm = useConfirm();
const [editing, setEditing] = useState(false);
const [name, setName] = useState(search.name);
const provider = config.providers.find((p) => p.id === search.provider)?.name ?? search.provider;
const commit = () => {
setEditing(false);
const n = name.trim();
if (!n || n === search.name) {
setName(search.name);
return;
}
update.mutate({ id: search.id, patch: { name: n } }, { onError: (e) => toast.error(buildError(e as unknown as AppError)) });
};
return (
<motion.li
layout
layoutId={`lead-search-${search.id}`}
initial={{ opacity: 0, y: -4 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, scale: 0.97 }}
transition={{ type: "spring", stiffness: 480, damping: 38, mass: 0.7 }}
onClick={() => !editing && onOpen()}
className={cn(
"group rounded-md border px-2.5 py-2 cursor-pointer transition-colors",
active ? "border-sky-300 bg-sky-50/60" : "border-slate-200 hover:border-slate-300 hover:bg-slate-50",
)}
>
<div className="flex items-center gap-1.5">
{editing ? (
<input
autoFocus
value={name}
maxLength={120}
onClick={(e) => e.stopPropagation()}
onChange={(e) => setName(e.target.value)}
onBlur={commit}
onKeyDown={(e) => {
if (e.key === "Enter") commit();
if (e.key === "Escape") {
setName(search.name);
setEditing(false);
}
}}
className="h-6 min-w-0 flex-1 rounded border border-sky-300 px-1.5 text-[12.5px] outline-none"
/>
) : (
// A real button, so the row opens from the keyboard; its click bubbles to the row.
<button
type="button"
aria-current={active || undefined}
className="min-w-0 flex-1 truncate rounded text-left text-[12.5px] font-medium text-slate-900 outline-none focus-visible:ring-2 focus-visible:ring-sky-200"
>
{search.name}
</button>
)}
<button
type="button"
aria-label={search.saved ? "Remove from saved" : "Save search"}
title={search.saved ? "Remove from saved" : "Save search"}
onClick={(e) => {
e.stopPropagation();
update.mutate({ id: search.id, patch: { saved: !search.saved } });
}}
className={cn(
"size-6 rounded inline-flex items-center justify-center",
search.saved ? "text-amber-500" : "text-slate-300 hover:text-slate-600 opacity-100 md:opacity-0 md:group-hover:opacity-100",
)}
>
<BookmarkIcon className={cn("size-3.5", search.saved && "fill-amber-400")} />
</button>
<PopoverMenu align="end">
<PopoverMenuTrigger asChild>
<button
type="button"
aria-label="More"
onClick={(e) => e.stopPropagation()}
className="size-6 rounded text-slate-400 hover:text-slate-700 hover:bg-white inline-flex items-center justify-center"
>
<MoreHorizontalIcon className="size-3.5" />
</button>
</PopoverMenuTrigger>
<PopoverMenuContent minWidth={170}>
<PopoverMenuItem icon={<PencilIcon className="size-3.5" />} onSelect={() => setEditing(true)}>
Rename
</PopoverMenuItem>
<PopoverMenuSeparator />
<PopoverMenuItem
danger
icon={<Trash2Icon className="size-3.5" />}
onSelect={() =>
confirm?.show(`Delete "${search.name}"? The leads it found stay in your list.`, async () => {
try {
await remove.mutateAsync(search.id);
onDelete();
} catch (e) {
toast.error(buildError(e as AppError));
}
})
}
>
Delete search
</PopoverMenuItem>
</PopoverMenuContent>
</PopoverMenu>
</div>
<div className="mt-0.5 flex items-center gap-1.5 text-[11px] text-slate-500">
<span>{search.result_count.toLocaleString()} leads</span>
<span className="text-slate-300">·</span>
<span className="truncate">{provider}</span>
<span className="ml-auto shrink-0 text-slate-400">{timeAgo(search.last_run_at)}</span>
</div>
</motion.li>
);
}
@@ -0,0 +1,335 @@
import { useMemo, useState } from "react";
import { Link } from "@tanstack/react-router";
import { AnimatePresence, motion } from "framer-motion";
import {
CheckIcon,
ChevronDownIcon,
CircleIcon,
DatabaseIcon,
Loader2Icon,
LockIcon,
PentagonIcon,
SearchIcon,
SquareIcon,
XIcon,
} from "lucide-react";
import { PopoverMenu, PopoverMenuContent, PopoverMenuItem, PopoverMenuLabel, PopoverMenuSeparator, PopoverMenuTrigger } from "@/components/ui/popover-menu";
import type { GeocodeResult, LatLng, LeadArea, LeadCategory, LeadFinderConfig, LeadProvider } from "@/lib/api/models/app/leads/Lead";
import { cn } from "@/lib/utils";
import LocationSearch from "./LocationSearch";
import SourceLogo from "./SourceLogo";
import { describeArea } from "./geo";
import type { MapTool } from "./LeadMap";
// Shown as one-tap chips; the rest live in the full list.
const QUICK = ["restaurant", "dentist", "gym", "hair_salon", "plumber", "real_estate", "lawyer", "cafe", "car_repair", "hotel"];
export default function SearchPanel({
config,
query,
onQuery,
category,
onCategory,
location,
onLocation,
onPlace,
near,
provider,
onProvider,
area,
onClearArea,
onTool,
searching,
onSearch,
blockedReason,
}: {
config: LeadFinderConfig;
query: string;
onQuery: (v: string) => void;
category: string;
onCategory: (id: string) => void;
location: string;
onLocation: (v: string) => void;
onPlace: (r: GeocodeResult) => void;
near: LatLng | null;
provider: LeadProvider;
onProvider: (p: LeadProvider) => void;
area: LeadArea | null;
onClearArea: () => void;
onTool: (t: MapTool) => void;
searching: boolean;
onSearch: () => void;
blockedReason: string | null;
}) {
const current = config.providers.find((p) => p.id === provider);
const picked = config.categories.find((c) => c.id === category);
const quick = QUICK.map((id) => config.categories.find((c) => c.id === id)).filter(Boolean) as LeadCategory[];
return (
<div className="space-y-3.5">
<div>
<div className="mb-1.5 text-[10px] font-medium uppercase tracking-[0.14em] text-slate-400">What</div>
<div className="relative">
<SearchIcon className="absolute left-2 top-1/2 -translate-y-1/2 size-3.5 text-slate-400" />
<input
value={query}
onChange={(e) => onQuery(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && !blockedReason && !searching && onSearch()}
maxLength={120}
placeholder={picked ? `${picked.label}, optionally named…` : "Business type or name, e.g. vegan bakery"}
aria-label="What to look for"
className="h-8 w-full rounded-md border border-slate-200 bg-white pl-7 pr-2 text-[12.5px] text-slate-900 placeholder:text-slate-400 outline-none focus:border-sky-400 focus:ring-2 focus:ring-sky-100"
/>
</div>
<div className="mt-2 flex flex-wrap gap-1">
<AnimatePresence initial={false} mode="popLayout">
{picked && !QUICK.includes(picked.id) && (
<Chip key={picked.id} on onClick={() => onCategory("")}>
{picked.label}
<XIcon className="size-3" />
</Chip>
)}
</AnimatePresence>
{quick.map((c) => (
<Chip key={c.id} on={category === c.id} onClick={() => onCategory(category === c.id ? "" : c.id)}>
{c.label}
</Chip>
))}
<CategoryMenu categories={config.categories} value={category} onChange={onCategory} />
</div>
</div>
<div>
<div className="mb-1.5 text-[10px] font-medium uppercase tracking-[0.14em] text-slate-400">Where</div>
<LocationSearch value={location} onChange={onLocation} near={near} onPick={onPlace} />
<div className="mt-2 flex items-center gap-1.5">
<span className="relative min-w-0 flex-1 overflow-hidden text-[11.5px]">
<AnimatePresence mode="wait" initial={false}>
<motion.span
key={area ? describeArea(area) : "view"}
initial={{ opacity: 0, y: 4 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -4 }}
transition={{ duration: 0.14 }}
className={cn("block truncate", area ? "font-medium text-sky-700" : "text-slate-500")}
>
{area ? describeArea(area) : "The visible map, or draw an area"}
</motion.span>
</AnimatePresence>
</span>
<ToolButton label="Draw a rectangle" onClick={() => onTool("rect")}>
<SquareIcon className="size-3.5" />
</ToolButton>
<ToolButton label="Draw a circle" onClick={() => onTool("circle")}>
<CircleIcon className="size-3.5" />
</ToolButton>
<ToolButton label="Draw a shape" onClick={() => onTool("polygon")}>
<PentagonIcon className="size-3.5" />
</ToolButton>
<AnimatePresence initial={false}>
{area && (
<motion.span key="clear" initial={{ opacity: 0, scale: 0.6 }} animate={{ opacity: 1, scale: 1 }} exit={{ opacity: 0, scale: 0.6 }} transition={{ duration: 0.14 }}>
<ToolButton label="Use the visible map instead" onClick={onClearArea}>
<XIcon className="size-3.5" />
</ToolButton>
</motion.span>
)}
</AnimatePresence>
</div>
</div>
<div>
<div className="mb-1.5 text-[10px] font-medium uppercase tracking-[0.14em] text-slate-400">Source</div>
<PopoverMenu>
<PopoverMenuTrigger asChild>
<button
type="button"
className="h-8 w-full rounded-md border border-slate-200 bg-white px-2 text-left inline-flex items-center gap-2 text-[12.5px] text-slate-800 hover:border-slate-300"
>
{current ? <SourceLogo provider={current.id} name={current.name} /> : <DatabaseIcon className="size-3.5 text-slate-400" />}
<span className="truncate">{current?.name ?? "Pick a source"}</span>
{current && current.key_source !== "none" && (
<span className="rounded bg-slate-100 px-1 text-[10px] text-slate-500">{current.key_source === "workspace" ? "your key" : "included"}</span>
)}
<ChevronDownIcon className="ml-auto size-3.5 text-slate-400" />
</button>
</PopoverMenuTrigger>
<PopoverMenuContent minWidth={300} matchTriggerWidth>
<PopoverMenuLabel>Where businesses come from</PopoverMenuLabel>
{config.providers.map((p) => (
<PopoverMenuItem
key={p.id}
disabled={!p.available}
selected={p.id === provider}
onSelect={() => onProvider(p.id)}
icon={<SourceLogo provider={p.id} name={p.name} size={7} />}
trailing={p.id === provider ? <CheckIcon className="size-3.5 text-sky-600" /> : !p.available ? <LockIcon className="size-3 text-slate-400" /> : undefined}
description={
!p.available
? "Connect a key under Integrations"
: p.credit_cost > 0
? `${p.credit_cost} credit a page of ${p.page_size}`
: p.key_source === "workspace"
? "Billed to your own account"
: "Free, no key needed"
}
>
{p.name}
</PopoverMenuItem>
))}
<PopoverMenuSeparator />
<div className="px-2.5 py-1.5">
<Link to="/app/integrations/$" params={{ _splat: "category/data" }} className="text-[11.5px] text-sky-700 hover:underline">
Connect Google Places, Foursquare or Outscraper
</Link>
</div>
</PopoverMenuContent>
</PopoverMenu>
<AnimatePresence mode="wait" initial={false}>
{current && (
<motion.p
key={current.id}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.14 }}
className="mt-1.5 text-[11px] leading-relaxed text-slate-400"
>
{current.description}
</motion.p>
)}
</AnimatePresence>
</div>
<div>
<motion.button
type="button"
disabled={searching || !!blockedReason}
onClick={onSearch}
whileTap={searching || blockedReason ? undefined : { scale: 0.98 }}
className="relative h-8 w-full overflow-hidden rounded-md bg-sky-600 text-white text-[12.5px] font-medium inline-flex items-center justify-center gap-1.5 hover:bg-sky-700 disabled:opacity-50 disabled:hover:bg-sky-600 transition-colors"
>
{searching && <span className="absolute inset-y-0 w-1/3 bg-white/20 progress-sweep" aria-hidden />}
<AnimatePresence mode="wait" initial={false}>
<motion.span
key={searching ? "busy" : area ? "area" : "view"}
initial={{ opacity: 0, y: 5 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -5 }}
transition={{ duration: 0.14 }}
className="relative inline-flex items-center gap-1.5"
>
{searching ? <Loader2Icon className="size-3.5 animate-spin" /> : <SearchIcon className="size-3.5" />}
{searching ? "Searching…" : area ? "Search this area" : "Search the visible map"}
</motion.span>
</AnimatePresence>
</motion.button>
<AnimatePresence initial={false}>
{blockedReason && (
<motion.p
initial={{ opacity: 0, height: 0 }}
animate={{ opacity: 1, height: "auto" }}
exit={{ opacity: 0, height: 0 }}
transition={{ duration: 0.18 }}
className="overflow-hidden pt-1.5 text-[11px] text-amber-700"
>
{blockedReason}
</motion.p>
)}
</AnimatePresence>
</div>
</div>
);
}
// Takes a ref so popLayout can pull an exiting chip out of the flow at once.
function Chip({ on, onClick, children, ref }: { on?: boolean; onClick: () => void; children: React.ReactNode; ref?: React.Ref<HTMLButtonElement> }) {
return (
<motion.button
ref={ref}
layout
type="button"
onClick={onClick}
aria-pressed={!!on}
initial={{ opacity: 0, scale: 0.85 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.85 }}
whileTap={{ scale: 0.94 }}
transition={{ type: "spring", stiffness: 520, damping: 34, mass: 0.6 }}
className={cn(
"h-6 px-2 rounded-full border text-[11.5px] inline-flex items-center gap-1 transition-colors",
on ? "border-sky-300 bg-sky-50 text-sky-700" : "border-slate-200 bg-white text-slate-600 hover:border-slate-300 hover:text-slate-900",
)}
>
{children}
</motion.button>
);
}
function ToolButton({ label, onClick, children }: { label: string; onClick: () => void; children: React.ReactNode }) {
return (
<button
type="button"
title={label}
aria-label={label}
onClick={onClick}
className="size-6 rounded-md border border-slate-200 bg-white text-slate-500 hover:text-slate-900 hover:border-slate-300 inline-flex items-center justify-center"
>
{children}
</button>
);
}
function CategoryMenu({ categories, value, onChange }: { categories: LeadCategory[]; value: string; onChange: (id: string) => void }) {
const [q, setQ] = useState("");
const groups = useMemo(() => {
const needle = q.trim().toLowerCase();
const out = new Map<string, LeadCategory[]>();
for (const c of categories) {
if (needle && !c.label.toLowerCase().includes(needle) && !c.group.toLowerCase().includes(needle)) continue;
out.set(c.group, [...(out.get(c.group) ?? []), c]);
}
return [...out.entries()];
}, [categories, q]);
return (
<PopoverMenu onOpenChange={(o) => !o && setQ("")}>
<PopoverMenuTrigger asChild>
<button
type="button"
className="h-6 px-2 rounded-full border border-dashed border-slate-300 text-[11.5px] text-slate-500 hover:text-slate-900 hover:border-slate-400 inline-flex items-center gap-1"
>
All {categories.length} categories
<ChevronDownIcon className="size-3" />
</button>
</PopoverMenuTrigger>
<PopoverMenuContent minWidth={280} role="dialog" aria-label="Categories">
<div className="p-1.5 border-b border-slate-100">
<input
autoFocus
value={q}
onChange={(e) => setQ(e.target.value)}
placeholder="Search categories…"
className="h-7 w-full rounded border border-slate-200 px-2 text-[12px] outline-none focus:border-sky-400"
/>
</div>
<div className="max-h-[320px] overflow-y-auto py-1">
{groups.length === 0 && <div className="px-3 py-4 text-center text-[11.5px] text-slate-400">No category matches</div>}
{groups.map(([group, list]) => (
<div key={group}>
<PopoverMenuLabel>{group}</PopoverMenuLabel>
{list.map((c) => (
<PopoverMenuItem
key={c.id}
onSelect={() => onChange(value === c.id ? "" : c.id)}
trailing={value === c.id ? <CheckIcon className="size-3.5 text-sky-600" /> : undefined}
>
{c.label}
</PopoverMenuItem>
))}
</div>
))}
</div>
</PopoverMenuContent>
</PopoverMenu>
);
}
@@ -0,0 +1,10 @@
import ProviderGlyph from "@/app/app/integrations/_components/ProviderGlyph";
import type { GlyphSize } from "@/app/app/integrations/_components/glyphSize";
import type { LeadProvider } from "@/lib/api/models/app/leads/Lead";
// OpenStreetMap is not an integration, so its mark is filed under its own name.
const GLYPH: Record<LeadProvider, string> = { osm: "openstreetmap", google_places: "google_places", foursquare: "foursquare", outscraper: "outscraper" };
export default function SourceLogo({ provider, name, size = 5 }: { provider: LeadProvider; name: string; size?: GlyphSize }) {
return <ProviderGlyph provider={GLYPH[provider]} name={name} size={size} />;
}
+43
View File
@@ -0,0 +1,43 @@
import { MailIcon } from "lucide-react";
import type { Lead, LeadStatus } from "@/lib/api/models/app/leads/Lead";
import { cn } from "@/lib/utils";
import { STATUS_LABEL, emailVerdict } from "./verdict";
const STATUS_STYLE: Record<LeadStatus, string> = {
new: "bg-slate-100 text-slate-600",
saved: "bg-violet-50 text-violet-700",
contacted: "bg-emerald-50 text-emerald-700",
dismissed: "bg-slate-100 text-slate-500",
};
export function StatusBadge({ status }: { status: LeadStatus }) {
return <span className={cn("inline-flex h-5 items-center rounded px-1.5 text-[10.5px] font-medium", STATUS_STYLE[status])}>{STATUS_LABEL[status]}</span>;
}
export function ScoreBar({ score }: { score: number }) {
const tone = score >= 70 ? "bg-sky-700" : score >= 40 ? "bg-sky-500" : "bg-slate-300";
return (
<div className="flex items-center gap-1.5" title={`Reachability score ${score} of 100`}>
<div className="h-1.5 flex-1 rounded-full bg-slate-100 overflow-hidden">
<div className={cn("h-full rounded-full", tone)} style={{ width: `${Math.max(4, score)}%` }} />
</div>
<span className="w-5 text-right text-[10.5px] tabular-nums text-slate-500">{score}</span>
</div>
);
}
export function EmailBadge({ lead }: { lead: Lead }) {
const primary = lead.emails.find((e) => e.email === lead.email);
const v = emailVerdict(primary);
const more = lead.emails.filter((e) => e.email !== lead.email && e.status !== "invalid" && e.status !== "suppressed").length;
return (
<span className="inline-flex min-w-0 items-center gap-1 text-[11.5px]">
<MailIcon className="size-3 shrink-0 text-slate-400" />
<span className="truncate text-slate-800">{lead.email}</span>
<span className={cn("shrink-0", v.tone)} title={v.label}>
{v.icon}
</span>
{more > 0 && <span className="shrink-0 text-slate-400">+{more}</span>}
</span>
);
}
+93
View File
@@ -0,0 +1,93 @@
import type { LatLng, LeadArea, LeadBounds } from "@/lib/api/models/app/leads/Lead";
const EARTH_M = 6371000;
export function distanceM(a: LatLng, b: LatLng): number {
const la1 = (a.lat * Math.PI) / 180;
const la2 = (b.lat * Math.PI) / 180;
const dLat = la2 - la1;
const dLng = ((b.lng - a.lng) * Math.PI) / 180;
const h = Math.sin(dLat / 2) ** 2 + Math.cos(la1) * Math.cos(la2) * Math.sin(dLng / 2) ** 2;
return 2 * EARTH_M * Math.asin(Math.min(1, Math.sqrt(h)));
}
// circleRing approximates a circle as a closed ring of [lng, lat] points.
export function circleRing(center: LatLng, radiusM: number, steps = 72): [number, number][] {
const out: [number, number][] = [];
const lat = (center.lat * Math.PI) / 180;
const lng = (center.lng * Math.PI) / 180;
const d = radiusM / EARTH_M;
for (let i = 0; i <= steps; i++) {
const brg = (i / steps) * 2 * Math.PI;
const la = Math.asin(Math.sin(lat) * Math.cos(d) + Math.cos(lat) * Math.sin(d) * Math.cos(brg));
const lo = lng + Math.atan2(Math.sin(brg) * Math.sin(d) * Math.cos(lat), Math.cos(d) - Math.sin(lat) * Math.sin(la));
out.push([(lo * 180) / Math.PI, (la * 180) / Math.PI]);
}
return out;
}
export function boundsOf(points: LatLng[]): LeadBounds {
const b = { south: 90, north: -90, west: 180, east: -180 };
for (const p of points) {
b.south = Math.min(b.south, p.lat);
b.north = Math.max(b.north, p.lat);
b.west = Math.min(b.west, p.lng);
b.east = Math.max(b.east, p.lng);
}
return b;
}
export function circleBounds(center: LatLng, radiusM: number): LeadBounds {
return boundsOf(circleRing(center, radiusM, 16).map(([lng, lat]) => ({ lat, lng })));
}
export function inPolygon(poly: LatLng[], p: LatLng): boolean {
let inside = false;
for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
const a = poly[i];
const b = 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) inside = !inside;
}
return inside;
}
export function areaContains(area: LeadArea, p: LatLng): boolean {
if (area.kind === "circle") return distanceM(area.center, p) <= area.radius_m;
if (area.kind === "polygon") return inPolygon(area.polygon, p);
const b = area.bounds;
return p.lat >= b.south && p.lat <= b.north && p.lng >= b.west && p.lng <= b.east;
}
// areaRing is the shape drawn on the map for an area, as [lng, lat] points.
export function areaRing(area: LeadArea): [number, number][] {
if (area.kind === "circle") return circleRing(area.center, area.radius_m);
if (area.kind === "polygon") {
const ring = area.polygon.map((p) => [p.lng, p.lat] as [number, number]);
return ring.length ? [...ring, ring[0]] : ring;
}
const b = area.bounds;
return [
[b.west, b.south],
[b.east, b.south],
[b.east, b.north],
[b.west, b.north],
[b.west, b.south],
];
}
export function areaKm2(b: LeadBounds): number {
const mid = (((b.south + b.north) / 2) * Math.PI) / 180;
const h = (((b.north - b.south) * Math.PI) / 180) * EARTH_M;
const w = (((b.east - b.west) * Math.PI) / 180) * EARTH_M * Math.cos(mid);
return (h * w) / 1e6;
}
export function describeArea(area: LeadArea): string {
if (area.kind === "circle") {
const r = area.radius_m;
return `Circle, ${r >= 1000 ? `${(r / 1000).toFixed(r >= 10000 ? 0 : 1)} km` : `${Math.round(r)} m`} radius`;
}
const km = areaKm2(area.bounds);
const size = km >= 10 ? `${Math.round(km)} km²` : `${km.toFixed(1)} km²`;
return area.kind === "polygon" ? `Drawn area, ${size}` : `Map view, ${size}`;
}
+30
View File
@@ -0,0 +1,30 @@
import type { ColorBy } from "./LeadMap";
// What each pin color means, per coloring mode; matches the expressions in LeadMap.
export const LEGEND: Record<ColorBy, { color: string; label: string }[]> = {
reach: [
{ color: "#10b981", label: "Email" },
{ color: "#0ea5e9", label: "Website" },
{ color: "#f59e0b", label: "Phone only" },
{ color: "#94a3b8", label: "No contact" },
],
status: [
{ color: "#0ea5e9", label: "New" },
{ color: "#8b5cf6", label: "Saved" },
{ color: "#10b981", label: "Contacted" },
{ color: "#94a3b8", label: "Dismissed" },
],
score: [
{ color: "#cbd5e1", label: "0" },
{ color: "#7dd3fc", label: "35" },
{ color: "#0284c7", label: "70" },
{ color: "#0c4a6e", label: "100" },
],
rating: [
{ color: "#059669", label: "4.5+" },
{ color: "#10b981", label: "4+" },
{ color: "#f59e0b", label: "3+" },
{ color: "#f43f5e", label: "Under 3" },
{ color: "#94a3b8", label: "No rating" },
],
};
+97
View File
@@ -0,0 +1,97 @@
import type { Map as MapLibreMap } from "maplibre-gl";
// Warmbly's palette laid over any OpenMapTiles-shaped vector style, so the map
// reads as part of the dashboard rather than a stock basemap.
interface Palette {
background: string;
water: string;
waterLine: string;
green: string;
building: string;
road: string;
roadMajor: string;
casing: string;
boundary: string;
label: string;
labelHalo: string;
}
const LIGHT: Palette = {
background: "#f8fafc",
water: "#dbeefb",
waterLine: "#bfdcf3",
green: "#e8f5ee",
building: "#eef1f5",
road: "#ffffff",
roadMajor: "#ffffff",
casing: "#e2e8f0",
boundary: "#cbd5e1",
label: "#64748b",
labelHalo: "#f8fafc",
};
const DARK: Palette = {
background: "#0b1220",
water: "#0d2236",
waterLine: "#12304a",
green: "#0e1f1a",
building: "#131c2b",
road: "#1b2537",
roadMajor: "#243149",
casing: "#0b1220",
boundary: "#334155",
label: "#8a9ab0",
labelHalo: "#0b1220",
};
function set(map: MapLibreMap, id: string, prop: string, value: unknown) {
try {
map.setPaintProperty(id, prop, value);
} catch {
// A layer without the property keeps its own.
}
}
export function applyMapTheme(map: MapLibreMap, dark: boolean) {
const p = dark ? DARK : LIGHT;
const layers = map.getStyle()?.layers ?? [];
for (const layer of layers) {
const id = layer.id;
if (id.startsWith("leads-") || id.startsWith("area-")) continue;
const name = id.toLowerCase();
switch (layer.type) {
case "background":
set(map, id, "background-color", p.background);
break;
case "fill":
if (/water|ocean|lake/.test(name)) set(map, id, "fill-color", p.water);
else if (/park|wood|grass|forest|landcover|green|cemetery|pitch/.test(name)) set(map, id, "fill-color", p.green);
else if (/building/.test(name)) set(map, id, "fill-color", p.building);
else if (/landuse|residential|aeroway|industrial/.test(name)) set(map, id, "fill-color", p.background);
break;
case "fill-extrusion":
set(map, id, "fill-extrusion-color", p.building);
break;
case "line":
if (/water|river|stream|canal/.test(name)) set(map, id, "line-color", p.waterLine);
else if (/boundary|admin/.test(name)) set(map, id, "line-color", p.boundary);
else if (/casing|outline/.test(name)) set(map, id, "line-color", p.casing);
else if (/motorway|trunk|primary|major/.test(name)) set(map, id, "line-color", p.roadMajor);
else if (/road|highway|street|minor|secondary|tertiary|service|path|track|bridge|tunnel/.test(name)) set(map, id, "line-color", p.road);
break;
case "symbol":
// Other businesses' icons compete with the pins; names stay.
if (/poi/.test(name)) {
try {
map.setLayoutProperty(id, "visibility", "none");
} catch {
// Keep a layer that refuses to hide.
}
break;
}
set(map, id, "text-color", p.label);
set(map, id, "text-halo-color", p.labelHalo);
break;
}
}
}
+114
View File
@@ -0,0 +1,114 @@
import type { LeadFilter, LeadStatus } from "@/lib/api/models/app/leads/Lead";
export type ReachFilter = "email" | "people" | "website" | "phone" | "socials" | "no_website";
export interface Refine {
reach: ReachFilter[];
statuses: LeadStatus[];
hideContacts: boolean;
hideDismissed: boolean;
excludeChains: boolean;
minRating: number | null;
minReviews: number;
maxReviews: number;
minScore: number;
category: string;
tag: string;
inView: boolean;
}
export const EMPTY_REFINE: Refine = {
reach: [],
statuses: [],
hideContacts: false,
hideDismissed: true,
excludeChains: false,
minRating: null,
minReviews: 0,
maxReviews: 0,
minScore: 0,
category: "",
tag: "",
inView: false,
};
// refineFilter turns the panel's state into the API filter.
export function refineFilter(r: Refine): LeadFilter {
const f: LeadFilter = {};
if (r.reach.includes("email")) f.has_email = true;
if (r.reach.includes("people")) f.has_people = true;
if (r.reach.includes("website")) f.has_website = true;
if (r.reach.includes("no_website")) f.has_website = false;
if (r.reach.includes("phone")) f.has_phone = true;
if (r.reach.includes("socials")) f.has_socials = true;
if (r.hideContacts) f.in_contacts = false;
if (r.statuses.length) f.statuses = r.statuses;
else if (r.hideDismissed) f.statuses = ["new", "saved", "contacted"];
if (r.excludeChains) f.exclude_chains = true;
if (r.minRating != null) f.min_rating = r.minRating;
if (r.minReviews > 0) f.min_reviews = r.minReviews;
if (r.maxReviews > 0) f.max_reviews = r.maxReviews;
if (r.minScore > 0) f.min_score = r.minScore;
if (r.category) f.category = r.category;
if (r.tag) f.tag = r.tag;
return f;
}
export function refineCount(r: Refine): number {
const d = EMPTY_REFINE;
return (
r.reach.length +
r.statuses.length +
Number(r.hideContacts) +
Number(r.excludeChains) +
Number(r.hideDismissed !== d.hideDismissed) +
Number(r.minRating != null) +
Number(r.minReviews > 0) +
Number(r.maxReviews > 0) +
Number(r.minScore > 0) +
Number(!!r.category) +
Number(!!r.tag) +
Number(r.inView)
);
}
export interface RefineChip {
key: string;
label: string;
clear: (r: Refine) => Refine;
}
const REACH_LABEL: Record<ReachFilter, string> = {
email: "Has email",
people: "Has people",
website: "Has website",
phone: "Has phone",
socials: "Has socials",
no_website: "No website",
};
const STATUS_LABEL: Record<LeadStatus, string> = { new: "New", saved: "Saved", contacted: "Contacted", dismissed: "Dismissed" };
// refineChips lists each active filter as something the filter bar can show and clear.
export function refineChips(r: Refine): RefineChip[] {
const out: RefineChip[] = r.reach.map((id) => ({
key: `reach:${id}`,
label: REACH_LABEL[id],
clear: (x) => ({ ...x, reach: x.reach.filter((v) => v !== id) }),
}));
if (r.minRating != null) out.push({ key: "rating", label: `${r.minRating}+ stars`, clear: (x) => ({ ...x, minRating: null }) });
if (r.minReviews > 0) out.push({ key: "minReviews", label: `${r.minReviews}+ reviews`, clear: (x) => ({ ...x, minReviews: 0 }) });
if (r.maxReviews > 0) out.push({ key: "maxReviews", label: `Up to ${r.maxReviews} reviews`, clear: (x) => ({ ...x, maxReviews: 0 }) });
if (r.minScore > 0) out.push({ key: "minScore", label: `Score ${r.minScore}+`, clear: (x) => ({ ...x, minScore: 0 }) });
for (const s of r.statuses) {
out.push({ key: `status:${s}`, label: STATUS_LABEL[s], clear: (x) => ({ ...x, statuses: x.statuses.filter((v) => v !== s) }) });
}
if (r.category) out.push({ key: "category", label: r.category, clear: (x) => ({ ...x, category: "" }) });
if (r.tag) out.push({ key: "tag", label: `#${r.tag}`, clear: (x) => ({ ...x, tag: "" }) });
if (r.inView) out.push({ key: "inView", label: "In map view", clear: (x) => ({ ...x, inView: false }) });
if (r.hideContacts) out.push({ key: "hideContacts", label: "Not in contacts", clear: (x) => ({ ...x, hideContacts: false }) });
if (r.excludeChains) out.push({ key: "excludeChains", label: "No chains", clear: (x) => ({ ...x, excludeChains: false }) });
if (!r.hideDismissed && r.statuses.length === 0) out.push({ key: "dismissed", label: "Dismissed shown", clear: (x) => ({ ...x, hideDismissed: true }) });
return out;
}
+61
View File
@@ -0,0 +1,61 @@
import { CircleCheckIcon, CircleHelpIcon, CircleXIcon, ShieldAlertIcon, SparklesIcon, TriangleAlertIcon } from "lucide-react";
import type { LeadEmail, LeadPerson, LeadStatus } from "@/lib/api/models/app/leads/Lead";
export const STATUS_LABEL: Record<LeadStatus, string> = {
new: "New",
saved: "Saved",
contacted: "Contacted",
dismissed: "Dismissed",
};
export function emailVerdict(e?: LeadEmail): { label: string; tone: string; icon: React.ReactNode } {
switch (e?.status) {
case "valid":
return { label: "Valid", tone: "text-emerald-700", icon: <CircleCheckIcon className="size-3" /> };
case "risky":
return { label: "Risky", tone: "text-amber-700", icon: <TriangleAlertIcon className="size-3" /> };
case "invalid":
return { label: "Invalid", tone: "text-rose-700", icon: <CircleXIcon className="size-3" /> };
case "suppressed":
return { label: "Suppressed", tone: "text-slate-500", icon: <ShieldAlertIcon className="size-3" /> };
default:
return { label: "Unchecked", tone: "text-slate-500", icon: <CircleHelpIcon className="size-3" /> };
}
}
// What we know about a person's address, in words a prospector acts on.
export function personVerdict(p: LeadPerson): { label: string; tone: string; icon: React.ReactNode; hint: string } {
switch (p.email_status) {
case "valid":
return {
label: "Confirmed",
tone: "text-emerald-700",
icon: <CircleCheckIcon className="size-3" />,
hint: p.email_source === "pattern" ? "Worked out from the name and confirmed by their mail server" : "Their mail server confirmed this address",
};
case "risky":
return { label: "Risky", tone: "text-amber-700", icon: <TriangleAlertIcon className="size-3" />, hint: "The server accepts it but may not deliver" };
case "invalid":
return { label: "Not deliverable", tone: "text-rose-700", icon: <CircleXIcon className="size-3" />, hint: "Their mail server refused this address" };
case "suppressed":
return { label: "Suppressed", tone: "text-slate-500", icon: <ShieldAlertIcon className="size-3" />, hint: "On your suppression list, so it is never mailed" };
case "guessed":
return {
label: p.email_confidence >= 50 ? "Likely" : "Best guess",
tone: p.email_confidence >= 50 ? "text-sky-700" : "text-amber-700",
icon: <SparklesIcon className="size-3" />,
hint:
p.email_confidence >= 50
? "Follows the address shape this business uses; their server could not confirm it"
: "The most common address shape; nothing could confirm it",
};
case "unknown":
return { label: "Unconfirmed", tone: "text-slate-500", icon: <CircleHelpIcon className="size-3" />, hint: "Their mail server would not say" };
}
return {
label: p.email_source === "manual" ? "Typed in" : "Unchecked",
tone: "text-slate-500",
icon: <CircleHelpIcon className="size-3" />,
hint: "Not checked yet",
};
}
@@ -272,6 +272,7 @@ const ENUM_LABELS: Record<string, string> = {
automation: "Automation",
apollo: "Apollo",
clay: "Clay",
lead_finder: "Lead finder",
valid: "Valid",
risky: "Risky",
invalid: "Invalid",
+2
View File
@@ -28,6 +28,7 @@ import {
SettingsIcon,
ShieldCheckIcon,
UsersIcon,
MapPinnedIcon,
LockIcon,
PanelLeftCloseIcon,
PanelLeftOpenIcon,
@@ -162,6 +163,7 @@ const sections: NavSection[] = [
{ title: "Accounts", url: "/app/emails", icon: MailIcon, indicator: "accounts", advisorSurface: "emails", permission: "MANAGE_EMAILS", permissionLabel: "Manage mailboxes" },
{ title: "Campaigns", scoped: true, requires: "subscription", url: "/app/campaigns", icon: MegaphoneIcon, indicator: "campaigns", advisorSurface: "campaigns", permission: "VIEW_CAMPAIGNS", permissionLabel: "View campaigns" },
{ title: "Contacts", requires: "subscription", url: "/app/contacts", icon: UsersIcon, indicator: "contacts", advisorSurface: "contacts", permission: "VIEW_CONTACTS", permissionLabel: "View contacts" },
{ title: "Lead finder", requires: "subscription", url: "/app/leads", icon: MapPinnedIcon, permission: "VIEW_CONTACTS", permissionLabel: "View contacts" },
{ title: "Forms", requires: "subscription", url: "/app/forms", icon: ClipboardListIcon, permission: "VIEW_CONTACTS", permissionLabel: "View contacts" },
{ title: "Analytics", scoped: true, requires: "subscription", url: "/app/analytics", icon: BarChart3Icon, indicator: "analytics", permission: "VIEW_ANALYTICS", permissionLabel: "View analytics" },
{ title: "Deliverability", requires: "subscription", url: "/app/deliverability", icon: ShieldCheckIcon, advisorSurface: "deliverability", permission: "VIEW_ANALYTICS", permissionLabel: "View analytics" },
@@ -14,6 +14,7 @@ const FEATURE_BY_PREFIX: [string, string][] = [
["/app/unibox", "The unified inbox"],
["/app/campaigns", "Campaigns"],
["/app/contacts", "Contacts"],
["/app/leads", "The lead finder"],
["/app/analytics", "Analytics"],
["/app/deliverability", "Deliverability"],
["/app/crm", "The CRM"],
+13 -2
View File
@@ -381,6 +381,7 @@ export function PopoverMenuItem({
disabled = false,
closeOnSelect = true,
trailing,
description,
}: {
children: React.ReactNode;
onSelect?: () => void;
@@ -392,6 +393,8 @@ export function PopoverMenuItem({
/** Custom right-aligned content. When set, it replaces the default
* `selected` dot — e.g. pass a checkmark for multi-select menus. */
trailing?: React.ReactNode;
/** A second, muted line under the label; the row grows to fit it. */
description?: React.ReactNode;
}) {
const { setOpen } = useMenu();
return (
@@ -406,7 +409,8 @@ export function PopoverMenuItem({
if (closeOnSelect) setOpen(false);
}}
className={cn(
"w-full h-7 px-3 flex items-center gap-2 text-[12.5px] text-left transition-colors outline-none",
"w-full px-3 flex items-center gap-2 text-[12.5px] text-left transition-colors outline-none",
description ? "min-h-7 py-1.5" : "h-7",
danger
? "text-red-600 hover:bg-red-50 focus-visible:bg-red-50"
: "text-slate-700 hover:bg-slate-50 hover:text-slate-900 focus-visible:bg-slate-50 focus-visible:text-slate-900",
@@ -415,7 +419,14 @@ export function PopoverMenuItem({
)}
>
{icon && <span className={cn("shrink-0", danger ? "text-red-500" : "text-slate-400")}>{icon}</span>}
<span className="flex-1 truncate">{children}</span>
{description ? (
<span className="flex-1 min-w-0">
<span className="block truncate">{children}</span>
<span className="block truncate text-[11px] font-normal text-slate-400">{description}</span>
</span>
) : (
<span className="flex-1 truncate">{children}</span>
)}
{trailing !== undefined ? (
<span className="shrink-0">{trailing}</span>
) : selected ? (
+2
View File
@@ -566,6 +566,8 @@ export function useRealtimeEvents() {
['crm', 'owners'],
],
lead_sync_source: [['lead-sync', 'sources']],
lead: [['leads']],
lead_search: [['leads', 'searches']],
meeting: [['meetings'], ['meetings', 'summary']],
subscription: [['subscription'], ['organizations', 'limits']],
referral_credit: [['subscription']],
+141
View File
@@ -0,0 +1,141 @@
// Lead finder endpoints. Every call is scoped to the current workspace.
import type {
AddLeadsToContactsRequest,
AddLeadsToContactsResult,
GeocodeResult,
LatLng,
Lead,
LeadEnrichmentRun,
LeadExportFormat,
LeadExportRows,
LeadFacets,
LeadFilter,
LeadFinderConfig,
LeadPage,
LeadPatch,
LeadPerson,
LeadPersonInput,
LeadPoint,
LeadSearch,
LeadSearchRequest,
LeadSearchResult,
LeadSelection,
LeadSort,
} from "@/lib/api/models/app/leads/Lead";
import Request from "../../Request";
export async function getLeadFinderConfig(): Promise<LeadFinderConfig> {
return await Request<LeadFinderConfig>({ method: "GET", url: "/leads/config", authorization: true });
}
export async function geocodeLocation(q: string, near?: LatLng, signal?: AbortSignal): Promise<GeocodeResult[]> {
const params = new URLSearchParams({ q });
if (near) {
params.set("lat", near.lat.toFixed(4));
params.set("lng", near.lng.toFixed(4));
}
const lang = typeof navigator !== "undefined" ? navigator.language.slice(0, 2) : "";
if (lang) params.set("lang", lang);
const body = await Request<{ data: GeocodeResult[] }>({
method: "GET",
url: `/leads/geocode?${params.toString()}`,
authorization: true,
signal,
});
return body?.data ?? [];
}
export async function searchLeads(req: LeadSearchRequest): Promise<LeadSearchResult> {
return await Request<LeadSearchResult>({ method: "POST", url: "/leads/search", data: req, authorization: true });
}
export async function queryLeads(input: {
filter: LeadFilter;
sort: LeadSort;
limit?: number;
cursor?: string;
}): Promise<LeadPage> {
return await Request<LeadPage>({ method: "POST", url: "/leads/query", data: input, authorization: true });
}
export async function getLeadPoints(filter: LeadFilter): Promise<{ data: LeadPoint[]; truncated: boolean }> {
return await Request<{ data: LeadPoint[]; truncated: boolean }>({
method: "POST",
url: "/leads/points",
data: { filter },
authorization: true,
});
}
export async function getLeadFacets(filter: LeadFilter): Promise<LeadFacets> {
return await Request<LeadFacets>({ method: "POST", url: "/leads/facets", data: { filter }, authorization: true });
}
export async function getLead(id: string): Promise<Lead> {
return await Request<Lead>({ method: "GET", url: `/leads/${id}`, authorization: true });
}
export async function updateLead(id: string, patch: LeadPatch): Promise<Lead> {
return await Request<Lead>({ method: "PATCH", url: `/leads/${id}`, data: patch, authorization: true });
}
export async function updateLeads(input: LeadSelection & LeadPatch): Promise<{ updated: number }> {
return await Request<{ updated: number }>({ method: "PATCH", url: "/leads", data: input, authorization: true });
}
export async function deleteLeads(sel: LeadSelection): Promise<{ deleted: number }> {
return await Request<{ deleted: number }>({ method: "DELETE", url: "/leads", data: sel, authorization: true });
}
export async function enrichLeads(input: LeadSelection & { verify?: boolean; people?: boolean }): Promise<LeadEnrichmentRun> {
return await Request<LeadEnrichmentRun>({ method: "POST", url: "/leads/enrich", data: input, authorization: true });
}
export async function listLeadEnrichments(): Promise<LeadEnrichmentRun[]> {
const body = await Request<{ data: LeadEnrichmentRun[] }>({ method: "GET", url: "/leads/enrichments", authorization: true });
return body?.data ?? [];
}
export async function addLeadsToContacts(req: AddLeadsToContactsRequest): Promise<AddLeadsToContactsResult> {
return await Request<AddLeadsToContactsResult>({ method: "POST", url: "/leads/contacts", data: req, authorization: true });
}
export async function exportLeads(input: LeadSelection & { format: LeadExportFormat; columns?: string[]; rows?: LeadExportRows }): Promise<Blob> {
return await Request<Blob>({
method: "POST",
url: "/leads/export",
data: input,
authorization: true,
responseType: "blob",
});
}
export async function listLeadSearches(): Promise<LeadSearch[]> {
const body = await Request<{ data: LeadSearch[] }>({ method: "GET", url: "/leads/searches", authorization: true });
return body?.data ?? [];
}
export async function updateLeadSearch(id: string, patch: { name?: string; saved?: boolean }): Promise<LeadSearch> {
return await Request<LeadSearch>({ method: "PATCH", url: `/leads/searches/${id}`, data: patch, authorization: true });
}
export async function deleteLeadSearch(id: string): Promise<void> {
await Request<void>({ method: "DELETE", url: `/leads/searches/${id}`, authorization: true });
}
export async function addLeadPerson(leadId: string, input: LeadPersonInput): Promise<LeadPerson> {
return await Request<LeadPerson>({ method: "POST", url: `/leads/${leadId}/people`, data: input, authorization: true });
}
export async function updateLeadPerson(leadId: string, personId: string, patch: LeadPersonInput): Promise<LeadPerson> {
return await Request<LeadPerson>({ method: "PATCH", url: `/leads/${leadId}/people/${personId}`, data: patch, authorization: true });
}
export async function deleteLeadPerson(leadId: string, personId: string): Promise<void> {
await Request<void>({ method: "DELETE", url: `/leads/${leadId}/people/${personId}`, authorization: true });
}
export async function findLeadPersonEmail(leadId: string, personId: string): Promise<LeadPerson> {
return await Request<LeadPerson>({ method: "POST", url: `/leads/${leadId}/people/${personId}/find-email`, authorization: true });
}
+303
View File
@@ -0,0 +1,303 @@
import { infiniteQueryOptions, queryOptions, useInfiniteQuery, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
addLeadPerson,
addLeadsToContacts,
deleteLeadPerson,
deleteLeadSearch,
deleteLeads,
enrichLeads,
findLeadPersonEmail,
getLead,
getLeadFacets,
getLeadFinderConfig,
getLeadPoints,
listLeadEnrichments,
listLeadSearches,
queryLeads,
searchLeads,
updateLead,
updateLeadPerson,
updateLeadSearch,
updateLeads,
} from "@/lib/api/client/app/leads/leads";
import type { Lead, LeadEnrichmentRun, LeadFilter, LeadPatch, LeadPerson, LeadPersonInput, LeadPoint, LeadSearch, LeadSort } from "@/lib/api/models/app/leads/Lead";
// Everything under ["leads"] is refreshed by the realtime spine on entity_type "lead".
export const LEADS_KEY = ["leads"] as const;
export const leadFinderConfigQuery = queryOptions({
queryKey: [...LEADS_KEY, "config"],
queryFn: getLeadFinderConfig,
staleTime: 60_000,
});
export const leadSearchesQuery = queryOptions({
queryKey: [...LEADS_KEY, "searches"],
queryFn: listLeadSearches,
staleTime: 15_000,
});
export const leadsListQuery = (filter: LeadFilter, sort: LeadSort) =>
infiniteQueryOptions({
queryKey: [...LEADS_KEY, "list", filter, sort],
queryFn: ({ pageParam }) => queryLeads({ filter, sort, limit: 50, cursor: pageParam || undefined }),
initialPageParam: "",
getNextPageParam: (last) => last.pagination.next_cursor ?? undefined,
staleTime: 10_000,
});
export const leadPointsQuery = (filter: LeadFilter) =>
queryOptions({
queryKey: [...LEADS_KEY, "points", filter],
queryFn: () => getLeadPoints(filter),
staleTime: 10_000,
placeholderData: (prev) => prev,
});
export const leadFacetsQuery = (filter: LeadFilter) =>
queryOptions({
queryKey: [...LEADS_KEY, "facets", filter],
queryFn: () => getLeadFacets(filter),
staleTime: 30_000,
placeholderData: (prev) => prev,
});
export const leadQuery = (id: string) =>
queryOptions({ queryKey: [...LEADS_KEY, "lead", id], queryFn: () => getLead(id), staleTime: 10_000 });
export function useLeadFinderConfig() {
return useQuery(leadFinderConfigQuery);
}
export function useLeadSearches() {
return useQuery(leadSearchesQuery);
}
// live refetches while a website run is going, so each row turns over as its lead is read.
export function useLeadsList(filter: LeadFilter, sort: LeadSort, live = false) {
return useInfiniteQuery({ ...leadsListQuery(filter, sort), refetchInterval: live ? 3_000 : false });
}
export function useLeadPoints(filter: LeadFilter) {
return useQuery(leadPointsQuery(filter));
}
export function useLeadFacets(filter: LeadFilter) {
return useQuery(leadFacetsQuery(filter));
}
export function useLead(id: string | null) {
return useQuery({ ...leadQuery(id ?? ""), enabled: !!id });
}
export const runActive = (r: LeadEnrichmentRun) => r.status === "queued" || r.status === "running";
// Website reads report progress only by polling: there is no per-lead event.
export function useLeadEnrichments() {
return useQuery({
queryKey: [...LEADS_KEY, "enrichments"],
queryFn: listLeadEnrichments,
staleTime: 2_000,
refetchInterval: (q) => ((q.state.data ?? []).some(runActive) ? 2_000 : false),
});
}
function useInvalidateLeads() {
const qc = useQueryClient();
return () => qc.invalidateQueries({ queryKey: LEADS_KEY });
}
export function useSearchLeads() {
const invalidate = useInvalidateLeads();
return useMutation({ mutationFn: searchLeads, onSuccess: () => invalidate() });
}
// Patching a lead is predictable, so the drawer and the pins change at once.
export function useUpdateLead() {
const qc = useQueryClient();
return useMutation({
mutationFn: ({ id, patch }: { id: string; patch: LeadPatch }) => updateLead(id, patch),
onMutate: async ({ id, patch }) => {
const key = [...LEADS_KEY, "lead", id];
await qc.cancelQueries({ queryKey: key });
const prev = qc.getQueryData<Lead>(key);
if (prev) qc.setQueryData<Lead>(key, { ...prev, ...patch } as Lead);
const points = qc.getQueriesData<{ data: LeadPoint[]; truncated: boolean }>({ queryKey: [...LEADS_KEY, "points"] });
if (patch.status) {
for (const [k, v] of points) {
if (!v) continue;
qc.setQueryData(k, { ...v, data: v.data.map((p) => (p.id === id ? { ...p, status: patch.status! } : p)) });
}
}
return { prev, points, key };
},
onError: (_e, _v, ctx) => {
if (!ctx) return;
if (ctx.prev) qc.setQueryData(ctx.key, ctx.prev);
for (const [k, v] of ctx.points) qc.setQueryData(k, v);
},
onSettled: () => qc.invalidateQueries({ queryKey: LEADS_KEY }),
});
}
export function useUpdateLeads() {
const invalidate = useInvalidateLeads();
return useMutation({ mutationFn: updateLeads, onSettled: () => invalidate() });
}
// Removed leads leave the map before the server answers.
export function useDeleteLeads() {
const qc = useQueryClient();
return useMutation({
mutationFn: deleteLeads,
onMutate: async (sel) => {
if (!sel.lead_ids?.length) return { points: [] as [readonly unknown[], unknown][] };
const gone = new Set(sel.lead_ids);
await qc.cancelQueries({ queryKey: [...LEADS_KEY, "points"] });
const points = qc.getQueriesData<{ data: LeadPoint[]; truncated: boolean }>({ queryKey: [...LEADS_KEY, "points"] });
for (const [k, v] of points) {
if (v) qc.setQueryData(k, { ...v, data: v.data.filter((p) => !gone.has(p.id)) });
}
return { points };
},
onError: (_e, _v, ctx) => {
for (const [k, v] of ctx?.points ?? []) qc.setQueryData(k, v);
},
onSettled: () => qc.invalidateQueries({ queryKey: LEADS_KEY }),
});
}
export function useEnrichLeads() {
const invalidate = useInvalidateLeads();
return useMutation({ mutationFn: enrichLeads, onSuccess: () => invalidate() });
}
export function useAddLeadsToContacts() {
const qc = useQueryClient();
return useMutation({
mutationFn: addLeadsToContacts,
onSuccess: () => {
qc.invalidateQueries({ queryKey: LEADS_KEY });
qc.invalidateQueries({ queryKey: ["contacts"] });
},
});
}
export function useUpdateLeadSearch() {
const qc = useQueryClient();
return useMutation({
mutationFn: ({ id, patch }: { id: string; patch: { name?: string; saved?: boolean } }) => updateLeadSearch(id, patch),
onMutate: async ({ id, patch }) => {
const key = leadSearchesQuery.queryKey;
await qc.cancelQueries({ queryKey: key });
const prev = qc.getQueryData<LeadSearch[]>(key);
if (prev) qc.setQueryData<LeadSearch[]>(key, prev.map((s) => (s.id === id ? { ...s, ...patch } : s)));
return { prev };
},
onError: (_e, _v, ctx) => {
if (ctx?.prev) qc.setQueryData(leadSearchesQuery.queryKey, ctx.prev);
},
onSettled: () => qc.invalidateQueries({ queryKey: leadSearchesQuery.queryKey }),
});
}
export function useDeleteLeadSearch() {
const qc = useQueryClient();
return useMutation({
mutationFn: deleteLeadSearch,
onMutate: async (id) => {
const key = leadSearchesQuery.queryKey;
await qc.cancelQueries({ queryKey: key });
const prev = qc.getQueryData<LeadSearch[]>(key);
if (prev) qc.setQueryData<LeadSearch[]>(key, prev.filter((s) => s.id !== id));
return { prev };
},
onError: (_e, _v, ctx) => {
if (ctx?.prev) qc.setQueryData(leadSearchesQuery.queryKey, ctx.prev);
},
onSettled: () => qc.invalidateQueries({ queryKey: leadSearchesQuery.queryKey }),
});
}
// Finding a person's address is decided by the server, so these wait for it,
// then write the answer straight into the open lead.
function usePersonResult() {
const qc = useQueryClient();
return (person: LeadPerson) => {
const key = [...LEADS_KEY, "lead", person.lead_id];
const lead = qc.getQueryData<Lead>(key);
if (lead) {
const people = lead.people ?? [];
const exists = people.some((p) => p.id === person.id);
qc.setQueryData<Lead>(key, {
...lead,
people: exists ? people.map((p) => (p.id === person.id ? person : p)) : [...people, person],
people_count: exists ? lead.people_count : lead.people_count + 1,
});
}
qc.invalidateQueries({ queryKey: LEADS_KEY });
};
}
export function useAddLeadPerson() {
const settle = usePersonResult();
return useMutation({
mutationFn: ({ leadId, input }: { leadId: string; input: LeadPersonInput }) => addLeadPerson(leadId, input),
onSuccess: settle,
});
}
export function useFindLeadPersonEmail() {
const settle = usePersonResult();
return useMutation({
mutationFn: ({ leadId, personId }: { leadId: string; personId: string }) => findLeadPersonEmail(leadId, personId),
onSuccess: settle,
});
}
// Editing a name, title or link is predictable; a new address is checked first.
export function useUpdateLeadPerson() {
const qc = useQueryClient();
const settle = usePersonResult();
return useMutation({
mutationFn: ({ leadId, personId, patch }: { leadId: string; personId: string; patch: LeadPersonInput }) =>
updateLeadPerson(leadId, personId, patch),
onMutate: async ({ leadId, personId, patch }) => {
const key = [...LEADS_KEY, "lead", leadId];
await qc.cancelQueries({ queryKey: key });
const prev = qc.getQueryData<Lead>(key);
if (prev && patch.email === undefined) {
qc.setQueryData<Lead>(key, { ...prev, people: (prev.people ?? []).map((p) => (p.id === personId ? { ...p, ...patch } : p)) });
}
return { prev, key };
},
onError: (_e, _v, ctx) => {
if (ctx?.prev) qc.setQueryData(ctx.key, ctx.prev);
},
onSuccess: settle,
});
}
export function useDeleteLeadPerson() {
const qc = useQueryClient();
return useMutation({
mutationFn: ({ leadId, personId }: { leadId: string; personId: string }) => deleteLeadPerson(leadId, personId),
onMutate: async ({ leadId, personId }) => {
const key = [...LEADS_KEY, "lead", leadId];
await qc.cancelQueries({ queryKey: key });
const prev = qc.getQueryData<Lead>(key);
if (prev) {
qc.setQueryData<Lead>(key, {
...prev,
people: (prev.people ?? []).filter((p) => p.id !== personId),
people_count: Math.max(0, prev.people_count - 1),
});
}
return { prev, key };
},
onError: (_e, _v, ctx) => {
if (ctx?.prev) qc.setQueryData(ctx.key, ctx.prev);
},
onSettled: () => qc.invalidateQueries({ queryKey: LEADS_KEY }),
});
}
@@ -56,7 +56,8 @@ export type ContactSource =
| "form"
| "automation"
| "apollo"
| "clay";
| "clay"
| "lead_finder";
// One observed fact about the mailbox. Silence is never recorded: a contact
// who does not open or reply has said nothing about their address.
@@ -17,6 +17,9 @@ export type IntegrationProvider =
| "google_sheets"
| "apollo"
| "clay"
| "google_places"
| "foursquare"
| "outscraper"
| "millionverifier"
| "cleanmylist";
@@ -375,6 +378,9 @@ export const PROVIDER_LABELS: Record<IntegrationProvider, string> = {
google_sheets: "Google Sheets",
apollo: "Apollo",
clay: "Clay",
google_places: "Google Places",
foursquare: "Foursquare",
outscraper: "Outscraper",
millionverifier: "MillionVerifier",
cleanmylist: "CleanMyList",
};
+335
View File
@@ -0,0 +1,335 @@
// The lead finder: businesses found on a map, enriched from their websites.
export type LeadProvider = "osm" | "google_places" | "foursquare" | "outscraper";
export type LeadStatus = "new" | "saved" | "contacted" | "dismissed";
export type LeadEnrichmentStatus = "none" | "queued" | "done" | "no_website" | "failed";
export type LeadSort = "recent" | "score" | "rating" | "reviews" | "name";
export interface LatLng {
lat: number;
lng: number;
}
export interface LeadBounds {
south: number;
west: number;
north: number;
east: number;
}
export type LeadArea =
| { kind: "bbox"; bounds: LeadBounds }
| { kind: "circle"; bounds: LeadBounds; center: LatLng; radius_m: number }
| { kind: "polygon"; bounds: LeadBounds; polygon: LatLng[] };
export interface LeadEmail {
email: string;
source: string;
url?: string;
domain_match: boolean;
status?: "valid" | "risky" | "invalid" | "unknown" | "suppressed" | "";
sub_status?: string;
}
export interface LeadSite {
reachable: boolean;
final_url?: string;
https: boolean;
title?: string;
description?: string;
platform?: string;
signals?: string[];
phones?: string[];
pages?: number;
// How the domain builds a person's address, e.g. "first.last".
email_pattern?: string;
// The mail server accepts any address, so a worked-out one cannot be confirmed.
accepts_all?: boolean;
// The listing had no website; the finder worked this one out from the name and confirmed it.
found_website?: boolean;
error?: string;
checked_at?: string;
}
export type LeadSeniority = "owner" | "executive" | "manager" | "staff";
export type LeadPersonSource = "schema" | "page" | "imprint" | "email" | "linkedin" | "manual";
export type LeadPersonEmailSource = "" | "website" | "pattern" | "manual";
export interface LeadPerson {
id: string;
lead_id: string;
name: string;
first_name: string;
last_name: string;
title: string;
seniority: LeadSeniority;
email: string;
email_source: LeadPersonEmailSource;
// valid, risky, invalid, unknown, guessed (worked out, unconfirmed) or suppressed.
email_status: string;
email_confidence: number;
linkedin_url: string;
phone: string;
source: LeadPersonSource;
source_url: string;
contact_id: string | null;
created_at: string;
updated_at: string;
}
export interface LeadPersonInput {
name?: string;
first_name?: string;
last_name?: string;
title?: string;
email?: string;
linkedin_url?: string;
phone?: string;
}
export interface Lead {
id: string;
provider: LeadProvider;
external_id: string;
name: string;
category: string;
categories: string[];
address: string;
street: string;
city: string;
region: string;
postcode: string;
country: string;
latitude: number;
longitude: number;
phone: string;
website: string;
domain: string;
email: string;
emails: LeadEmail[];
socials: Record<string, string>;
rating: number | null;
review_count: number | null;
price_level: number | null;
hours: string[];
business_status: string;
maps_url: string;
description: string;
chain: string;
site: LeadSite;
score: number;
status: LeadStatus;
enrichment_status: LeadEnrichmentStatus;
enriched_at: string | null;
contact_id: string | null;
tags: string[];
notes: string;
people_count: number;
// Only on a lead read on its own.
people?: LeadPerson[];
first_seen_at: string;
last_seen_at: string;
created_at: string;
updated_at: string;
}
export interface LeadPoint {
id: string;
name: string;
category: string;
latitude: number;
longitude: number;
status: LeadStatus;
score: number;
has_email: boolean;
has_website: boolean;
has_phone: boolean;
rating: number | null;
review_count: number | null;
in_contacts: boolean;
}
export interface LeadSearch {
id: string;
created_by_user_id: string | null;
name: string;
provider: LeadProvider;
query: string;
category: string;
location_label: string;
area: LeadArea;
saved: boolean;
result_count: number;
pages_fetched: number;
has_more: boolean;
last_run_at: string;
created_at: string;
updated_at: string;
}
export interface LeadFilter {
search_id?: string;
q?: string;
statuses?: LeadStatus[];
providers?: LeadProvider[];
category?: string;
tag?: string;
has_email?: boolean;
has_website?: boolean;
has_phone?: boolean;
has_socials?: boolean;
has_people?: boolean;
in_contacts?: boolean;
enrichment?: LeadEnrichmentStatus[];
min_rating?: number;
min_reviews?: number;
max_reviews?: number;
min_score?: number;
bounds?: LeadBounds;
exclude_chains?: boolean;
}
export interface LeadSelection {
lead_ids?: string[];
all?: boolean;
filter?: LeadFilter;
}
export interface LeadPatch {
status?: LeadStatus;
notes?: string;
tags?: string[];
add_tags?: string[];
remove_tags?: string[];
}
export interface LeadProviderInfo {
id: LeadProvider;
name: string;
description: string;
available: boolean;
key_source: "none" | "workspace" | "instance";
needs_key: boolean;
page_size: number;
max_pages: number;
credit_cost: number;
fields: string[];
integration?: string;
}
export interface LeadCategory {
id: string;
label: string;
group: string;
}
export interface LeadExportColumn {
key: string;
label: string;
}
export interface LeadFinderConfig {
providers: LeadProviderInfo[];
categories: LeadCategory[];
default_provider: LeadProvider;
enrich_cost: number;
person_email_cost: number;
export_columns: LeadExportColumn[];
person_columns: LeadExportColumn[];
default_export_columns: string[];
map: { style_light: string; style_dark: string };
}
export interface GeocodeResult {
label: string;
detail: string;
kind: string;
center: LatLng;
bounds?: LeadBounds;
}
export interface LeadSearchRequest {
search_id?: string;
provider?: LeadProvider;
query?: string;
category?: string;
location_label?: string;
area?: LeadArea;
save?: boolean;
name?: string;
language?: string;
}
export interface LeadSearchResult {
search: LeadSearch;
leads: Lead[];
found: number;
outside_area: number;
credits_charged: number;
}
export interface LeadFacet {
value: string;
count: number;
}
export interface LeadFacets {
categories: LeadFacet[];
tags: LeadFacet[];
cities: LeadFacet[];
}
export interface LeadPage {
data: Lead[];
pagination: { next_cursor: string | null; has_more: boolean; total: number };
}
export interface LeadEnrichmentRun {
id: string;
requested_by_user_id: string | null;
verify: boolean;
people: boolean;
status: "queued" | "running" | "done" | "error";
total: number;
processed: number;
emails_found: number;
people_found: number;
no_website: number;
failed: number;
credits_consumed: number;
last_error: string;
started_at: string | null;
finished_at: string | null;
created_at: string;
updated_at: string;
}
export interface AddLeadsToContactsRequest extends LeadSelection {
campaign_ids?: string[];
category_ids?: string[];
segment_ids?: string[];
verified_only?: boolean;
who?: LeadContactsWho;
include_guessed?: boolean;
// Leave contacts already in the workspace as they are.
keep_existing?: boolean;
skip_active_in_other_campaigns?: boolean;
}
export type LeadContactsWho = "business" | "people" | "both";
export interface AddLeadsToContactsResult {
selected: number;
imported: number;
updated: number;
skipped: number;
failed: number;
no_email: number;
unverified: number;
suppressed: number;
guessed: number;
people: number;
}
export type LeadExportFormat = "csv" | "xlsx" | "json";
export type LeadExportRows = "leads" | "people";
+6
View File
@@ -30,6 +30,7 @@ import { readCachedView, viewPreferencesQuery } from "./lib/api/hooks/app/views/
import { labelCountQuery, segmentFieldsQuery, segmentQuery, segmentsListQuery } from "./lib/api/hooks/app/segments";
import { apolloOverviewQuery, apolloSourcesQuery } from "./lib/api/hooks/app/integrations/useApollo";
import { claySettingsQuery } from "./lib/api/hooks/app/integrations/useClay";
import { leadFinderConfigQuery, leadSearchesQuery } from "./lib/api/hooks/app/leads/useLeads";
import { suppressionsListQuery } from "./lib/api/hooks/app/suppressions/useSuppressions";
import { formQuery, formsListQuery } from "./lib/api/hooks/app/forms";
import { campaignsListQuery } from "./lib/api/hooks/app/campaigns/useCampaigns";
@@ -319,6 +320,11 @@ export const apolloLoader = pageLoader((qc, { params }) =>
export const clayLoader = pageLoader((qc, { params }) => [!!params.id && qc.prefetchQuery(claySettingsQuery(params.id))]);
export const leadsLoader = pageLoader((qc) => [
can("VIEW_CONTACTS") && qc.prefetchQuery(leadFinderConfigQuery),
can("VIEW_CONTACTS") && qc.prefetchQuery(leadSearchesQuery),
]);
export const auditLoader = pageLoader((qc) => [canManageTeam() && qc.prefetchQuery(auditLogsQuery({ limit: 50 }))]);
const UNIBOX_FOLDER_SCOPES: UniboxFolder[] = ["inbox", "sent", "drafts", "archive", "spam", "trash"];
+3
View File
@@ -57,6 +57,7 @@ export const dashboardPages = {
labels: () => import("./app/app/contacts/labels/page"),
suppressions: () => import("./app/app/contacts/suppressions/page"),
forms: () => import("./app/app/forms/page"),
leads: () => import("./app/app/leads/page"),
form: () => import("./app/app/forms/[id]/page"),
campaigns: () => import("./app/app/campaigns/page"),
campaignLayout: () => import("./app/app/campaigns/[id]/layout"),
@@ -346,6 +347,7 @@ const clayRoute = dash(appRoute, "integrations/clay/$id", dashboardPages.clay, "
const automationsRoute = dash(appRoute, "automations", dashboardPages.automations, "Automations", loaders.automationsLoader);
const automationRoute = dash(appRoute, "automations/$id", dashboardPages.automation, "Automation", loaders.automationLoader);
const auditRoute = dash(appRoute, "audit", dashboardPages.audit, "Audit log", loaders.auditLoader);
const leadsRoute = dash(appRoute, "leads", dashboardPages.leads, "Lead finder", loaders.leadsLoader);
// Link buttons sent before the link page moved out of the dashboard.
const appSlackLinkRoute = forward(appRoute, "slack/link", "/slack/link", true);
// The breadcrumb above the link page points here.
@@ -443,6 +445,7 @@ const routeTree = rootRoute.addChildren([
automationsRoute,
automationRoute,
auditRoute,
leadsRoute,
appSlackLinkRoute,
slackRoute,
settingsRoute.addChildren(settingsChildren),