Phase 7 part 3: suggestions from the funnel

A new package, next, finds the pages the funnel asks for: a landing page
for a signal with replies or interested people in 90 days and none yet;
a product or alternative page for an app two or more people name in
their replies (outreach email, origami.chat, explee.com) that the site
has no page for; and picked keywords with no brief, briefs left
unanswered. Sites → New pages can be filled in from a link (kind,
signal, notes).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-24 07:13:38 -07:00
co-authored by Claude Opus 5.5
parent 77f6e1e1d1
commit 855615ae7f
4 changed files with 428 additions and 4 deletions
+342
View File
@@ -0,0 +1,342 @@
// Package next works out what to write next for a website: the pages the
// funnel asks for (a signal that gets replies but has no landing page, an
// app people name in their replies with no page of its own, a keyword or a
// brief that stalled), to sit in one list with SEO's own suggestions.
// Nothing here writes anything: each suggestion carries the button that
// starts the existing flow, and the flow asks its questions first.
package next
import (
"fmt"
"net/url"
"regexp"
"slices"
"strconv"
"strings"
"time"
"supermarket/internal/db"
"supermarket/internal/inventory"
"supermarket/internal/profile"
"supermarket/internal/seo"
"supermarket/internal/signals"
"supermarket/internal/sites"
)
// Suggestion is one thing to write.
type Suggestion struct {
Key string // stable, for dismissing: kind:subject
Kind string // what it is, in words: "Landing page", "Product page"…
Title string
Why string // the numbers behind it
Score float64
Action Action
}
// Action is the button that starts the flow: a link (GET) or a form.
type Action struct {
Label string
Method string // GET or POST
URL string
Fields map[string]string
Busy string // the button's label while a POST runs
}
// Scores put the funnel's suggestions on roughly the same scale as SEO's
// (sign-ups expected in 90 days): a landing page wins about a tenth of the
// people who already replied to its signal, a page for an app about a
// tenth of the people who named it. They only order the list; the reason
// shown is the real numbers.
const (
perReply = 0.1
perMention = 0.1
stalledPick = 0.5
stalledBrief = 0.6
minMentions = 2
funnelDays = 90
maxMentionLen = 40
)
// SignalsWithoutPages are buying signals with replies or interested people
// in the last 90 days, and no landing page on any site yet.
func SignalsWithoutPages(d *db.DB, now time.Time) ([]Suggestion, error) {
rows, err := signals.Scorecard(d, signals.Filter{Since: now.AddDate(0, 0, -funnelDays)})
if err != nil {
return nil, err
}
var out []Suggestion
for _, r := range rows {
if r.Signal == nil || r.Signal.Status == "retired" {
continue
}
replied, interested := r.Counts[signals.StageReplied], r.Counts[signals.StageInterested]
if replied+interested == 0 {
continue
}
pages, err := sites.SignalPages(d, r.Signal.ID)
if err != nil {
return nil, err
}
has := false
for _, p := range pages {
if p.Status != sites.PageClosed && p.Status != sites.PageRemoved {
has = true
}
}
if has {
continue
}
id := strconv.FormatInt(r.Signal.ID, 10)
why := fmt.Sprintf("In 90 days, %s and %s, from outreach on this signal, and no landing page to send them to.",
count(replied, "reply", "replies"), count(interested, "interested person", "interested people"))
out = append(out, Suggestion{
Key: "signal-page:" + id, Kind: "Landing page", Title: r.Signal.Name, Why: why,
Score: perReply * float64(replied+interested),
Action: Action{Label: "Set up its landing page", Method: "GET",
URL: "/sites/pages?kind=landing&signal=" + id + "#new"},
})
}
return out, nil
}
// Mention is an app or product people named in their replies.
type Mention struct {
Name string
People int
Example string // a reply that names it, shortened
}
// AppsInReplies counts the people whose replies name each app or product
// (from the profile's technologies, the Inventory, the website's pages,
// and well-known apps), and keeps those with no page of their own on the
// site. pageTitles and pagePaths are the site's pages.
func AppsInReplies(d *db.DB, p *profile.Profile, pagePaths, pageTitles []string) ([]Mention, error) {
texts, err := replyTexts(d)
if err != nil {
return nil, err
}
names, err := vocabulary(d, p, pageTitles)
if err != nil {
return nil, err
}
var out []Mention
for _, name := range names {
re := regexp.MustCompile(`(?i)(^|[^\pL\pN])` + regexp.QuoteMeta(name) + `($|[^\pL\pN])`)
m := Mention{Name: name}
for _, t := range texts {
if re.MatchString(t) {
m.People++
if m.Example == "" {
m.Example = around(t, name)
}
}
}
if m.People >= minMentions && !hasPage(name, pagePaths, pageTitles) {
out = append(out, m)
}
}
slices.SortStableFunc(out, func(a, b Mention) int { return b.People - a.People })
return out, nil
}
// MentionSuggestions turn mentions into suggestions: a product page for an
// app the company offers (in the profile's products or the Inventory as a
// partner), else an alternative page for something its customers leave.
func MentionSuggestions(ms []Mention, p *profile.Profile) []Suggestion {
var out []Suggestion
for _, m := range ms {
kind, label, link := "Product page", "Set up its page", "/sites/pages?kind=product&notes="+url.QueryEscape("A page for "+m.Name+": people name it in their replies.")+"#new"
if p != nil && slices.ContainsFunc(p.Targets.Technologies, func(t string) bool { return strings.EqualFold(t, m.Name) }) {
kind, label = "Alternative page", "Set up an alternative page"
link = "/sites/pages?kind=alternative&notes=" + url.QueryEscape("For people leaving "+m.Name+": they name it in their replies. Add "+m.Name+" to the Inventory as a competitor first.") + "#new"
}
why := fmt.Sprintf("%s named it in their replies, and the site has no page for it.", count(m.People, "person", "people"))
if m.Example != "" {
why += " “" + m.Example + "”"
}
out = append(out, Suggestion{Key: "app:" + strings.ToLower(m.Name), Kind: kind, Title: m.Name, Why: why,
Score: perMention * float64(m.People), Action: Action{Label: label, Method: "GET", URL: link}})
}
return out
}
// Stalled are a site's picked keywords with no brief, and briefs left
// unanswered for more than a day.
func Stalled(d *db.DB, siteURL string, siteIndex int, now time.Time) ([]Suggestion, error) {
briefs, err := seo.Briefs(d, siteURL)
if err != nil {
return nil, err
}
briefed := map[string]bool{}
var out []Suggestion
for _, b := range briefs {
briefed[strings.ToLower(b.Keyword)] = true
if b.Status == seo.BriefDraft && now.Sub(b.CreatedAt) > 24*time.Hour {
out = append(out, Suggestion{
Key: "brief:" + strconv.FormatInt(b.ID, 10), Kind: "Brief to finish", Title: b.Keyword,
Why: fmt.Sprintf("Its brief has waited %s for your answers; the page is written once they're in.", since(now.Sub(b.CreatedAt))),
Score: stalledBrief,
Action: Action{Label: "Answer its questions", Method: "GET", URL: "/seo/briefs/" + strconv.FormatInt(b.ID, 10)},
})
}
}
picks, err := seo.Keywords(d, siteURL, seo.KeywordPicked)
if err != nil {
return nil, err
}
for _, k := range picks {
if briefed[strings.ToLower(k.Keyword)] {
continue
}
why := "You picked it"
if !k.PickedAt.IsZero() {
why += " " + since(now.Sub(k.PickedAt)) + " ago"
}
why += ", and it has no brief yet."
if k.Impressions > 0 {
why += fmt.Sprintf(" Google already shows the site for it: %s impressions at position %.1f.", seo.Thousands(k.Impressions), k.Position)
}
out = append(out, Suggestion{
Key: "keyword:" + strconv.FormatInt(k.ID, 10), Kind: "New page", Title: k.Keyword, Why: why, Score: stalledPick,
Action: Action{Label: "Write the brief (up to 5 web searches)", Method: "POST", URL: "/seo/briefs?site=" + strconv.Itoa(siteIndex),
Fields: map[string]string{"site_url": siteURL, "keyword": k.Keyword}, Busy: "Writing the brief…"},
})
}
return out, nil
}
// replyTexts are what people wrote back: replies to outreach email, and
// the replies and notes the lead tools sent with each person.
func replyTexts(d *db.DB) ([]string, error) {
var out []string
rows, err := d.Query(`SELECT reply FROM outreach WHERE reply != ''
UNION ALL SELECT source_detail FROM prospect_contacts WHERE source_detail LIKE '%”: %'`)
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var t string
if err := rows.Scan(&t); err != nil {
return nil, err
}
// A lead tool's note starts with its campaign's name, which isn't
// what the person said.
if _, after, ok := strings.Cut(t, "”: "); ok {
t = after
}
out = append(out, t)
}
return out, rows.Err()
}
// wellKnown are apps people often name: the ones a business leaves, and
// open-source ones it might run instead.
var wellKnown = []string{
"Google Workspace", "Gmail", "Google Drive", "Microsoft 365", "Office 365", "Outlook", "SharePoint", "OneDrive", "Teams",
"Slack", "Zoom", "Dropbox", "Box", "Salesforce", "HubSpot", "Zendesk", "Help Scout", "Freshdesk", "Intercom",
"Mailchimp", "QuickBooks", "Xero", "Jira", "Confluence", "Asana", "Trello", "Monday", "Notion", "Airtable",
"Planning Center", "Calendly", "DocuSign", "1Password", "LastPass",
"Nextcloud", "Jitsi", "Element", "Matrix", "Mattermost", "Rocket.Chat", "EspoCRM", "SuiteCRM", "Odoo", "ERPNext",
"FreeScout", "Discourse", "Gitea", "GitLab", "WordPress", "Ghost", "BookStack", "Wiki.js", "Vaultwarden", "Bitwarden",
"Plausible", "Matomo", "n8n", "Baserow", "NocoDB", "Immich", "Paperless", "Listmonk", "Mautic", "Cal.com",
"DocuSeal", "Plane", "Kimai", "Castopod", "Roundcube", "Headscale", "Collabora", "OnlyOffice", "Moodle",
}
// vocabulary is the app and product names to look for in replies.
func vocabulary(d *db.DB, p *profile.Profile, pageTitles []string) ([]string, error) {
var names []string
add := func(n string) {
n = strings.TrimSpace(n)
if n == "" || len(n) > maxMentionLen || slices.ContainsFunc(names, func(x string) bool { return strings.EqualFold(x, n) }) {
return
}
names = append(names, n)
}
for _, n := range wellKnown {
add(n)
}
if p != nil {
for _, t := range p.Targets.Technologies {
add(t)
}
}
entries, err := inventory.List(d, "")
if err != nil {
return nil, err
}
for _, e := range entries {
add(e.Name)
}
return names, nil
}
// hasPage says whether the site has a page of an app's own: its address
// or its title is the app's name.
func hasPage(name string, paths, titles []string) bool {
slug := strings.Trim(regexp.MustCompile(`[^a-z0-9]+`).ReplaceAllString(strings.ToLower(name), "-"), "-")
for _, p := range paths {
last := strings.Trim(p, "/")
if i := strings.LastIndex(last, "/"); i >= 0 {
last = last[i+1:]
}
if last == slug || strings.HasPrefix(last, slug+"-") {
return true
}
}
for _, t := range titles {
head, _, _ := strings.Cut(t, " — ")
head, _, _ = strings.Cut(head, " | ")
head, _, _ = strings.Cut(head, ":")
if strings.EqualFold(strings.TrimSpace(head), name) {
return true
}
}
return false
}
// around is a short piece of a reply around a name.
func around(text, name string) string {
i := strings.Index(strings.ToLower(text), strings.ToLower(name))
if i < 0 {
return ""
}
start := max(0, i-60)
end := min(len(text), i+len(name)+60)
for start > 0 && !utf8Start(text[start]) {
start--
}
for end < len(text) && !utf8Start(text[end]) {
end++
}
s := strings.Join(strings.Fields(text[start:end]), " ")
if start > 0 {
s = "…" + s
}
if end < len(text) {
s += "…"
}
return s
}
func utf8Start(b byte) bool { return b&0xC0 != 0x80 }
func count(n int, one, many string) string {
if n == 1 {
return "1 " + one
}
return strconv.Itoa(n) + " " + many
}
func since(d time.Duration) string {
switch days := int(d.Hours() / 24); {
case days < 1:
return "less than a day"
case days == 1:
return "a day"
case days < 14:
return strconv.Itoa(days) + " days"
default:
return strconv.Itoa(days/7) + " weeks"
}
}