Everything the user sees says Market: the sidebar, titles, breadcrumbs, help text, messages, suggestions and the agent tool's description; the export downloads as supermarket-market.yaml. Its pages live under /market, and the old /inventory addresses redirect there (308, so a form's POST stays a POST). The YAML format (inventory:), the database and the code's names are unchanged, so exported files still import. A breadcrumb no longer repeats the page's own title. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
459 lines
16 KiB
Go
459 lines
16 KiB
Go
// 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)
|
|
got := count(replied, "reply", "replies")
|
|
switch {
|
|
case replied == 0:
|
|
got = count(interested, "interested person", "interested people")
|
|
case interested > 0:
|
|
got += " and " + count(interested, "interested person", "interested people")
|
|
}
|
|
why := fmt.Sprintf("In 90 days, %s from outreach on this signal, and no landing page to send them to.", got)
|
|
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¬es="+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¬es=" + url.QueryEscape("For people leaving "+m.Name+": they name it in their replies. Add "+m.Name+" to the Market 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, ownWords(t))
|
|
}
|
|
return out, rows.Err()
|
|
}
|
|
|
|
// quoteStart marks where a reply stops being the person's own words: the
|
|
// message they're answering, quoted below, in the usual languages.
|
|
var quoteStart = regexp.MustCompile(`(?im)(^\s*>|^\s*-{2,}\s*(original message|ursprüngliche nachricht|message d'origine|ursprungligt meddelande)|(^|\s)(from|från|fra|de|von|van|da|od)\s*:\s|\bon .{3,80} wrote:|\bam .{3,80} schrieb|\ble .{3,80} a écrit)`)
|
|
|
|
// signature drops "Sent from…" lines a phone or mail app adds.
|
|
var signature = regexp.MustCompile(`(?i)\b(sent|skickat|sendt|envoyé|gesendet|enviado|inviato|verzonden|wysłane)\s+(from|från|fra|de|depuis|von|desde|da|met|z)\s+\S+(\s+\S+){0,4}`)
|
|
|
|
// ownWords is the part of a reply the person wrote.
|
|
func ownWords(t string) string {
|
|
if loc := quoteStart.FindStringIndex(t); loc != nil {
|
|
t = t[:loc[0]]
|
|
}
|
|
return signature.ReplaceAllString(t, " ")
|
|
}
|
|
|
|
// 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"
|
|
}
|
|
}
|
|
|
|
// SectionPage is a page built from sections, as Sites reads it.
|
|
type SectionPage struct {
|
|
Path, Title string
|
|
Types []string
|
|
}
|
|
|
|
// question spots searches that ask something.
|
|
var question = regexp.MustCompile(`(?i)^(how|what|why|when|where|which|who|can|does|do|is|are|should|will)\b|\?$`)
|
|
|
|
// comparing spots searches that compare or look for something else.
|
|
var comparing = regexp.MustCompile(`(?i)\b(vs\.?|versus|alternatives?|compared?|comparison)\b`)
|
|
|
|
// minSectionImpr is how many impressions a page's questions (or
|
|
// comparisons) need, together, before a section is suggested for them.
|
|
const minSectionImpr = 50
|
|
|
|
// SectionIdeas suggest a section for a page already on the site: a FAQ
|
|
// when people find it with questions and it has none, a comparison table
|
|
// when they search it against something else (an alternative, a "vs", a
|
|
// competitor by name) and it has none. Only types the site has.
|
|
func SectionIdeas(pages []SectionPage, searches map[string][]seo.QueryRow, siteTypes, competitors []string, siteIndex int, rate float64) []Suggestion {
|
|
has := func(list []string, t string) bool { return slices.Contains(list, t) }
|
|
faq := firstOf(siteTypes, "faq", "faqs", "questions")
|
|
table := firstOf(siteTypes, "comparison", "compare", "table", "matrix")
|
|
var out []Suggestion
|
|
for _, pg := range pages {
|
|
qs := searches[seo.PathKey(pg.Path)]
|
|
var asks, vs []string
|
|
askImpr, vsImpr := 0, 0
|
|
for _, q := range qs {
|
|
switch {
|
|
case question.MatchString(q.Query):
|
|
asks = append(asks, q.Query)
|
|
askImpr += q.Impressions
|
|
case comparing.MatchString(q.Query) || slices.ContainsFunc(competitors, func(c string) bool {
|
|
return c != "" && strings.Contains(strings.ToLower(q.Query), strings.ToLower(c))
|
|
}):
|
|
vs = append(vs, q.Query)
|
|
vsImpr += q.Impressions
|
|
}
|
|
}
|
|
link := func(typ string, notes string) Action {
|
|
return Action{Label: "Write the section", Method: "GET",
|
|
URL: "/sites/pages/add?site=" + strconv.Itoa(siteIndex) + "&page=" + url.QueryEscape(pg.Path) + "&type=" + url.QueryEscape(typ) + "¬es=" + url.QueryEscape(notes)}
|
|
}
|
|
if faq != "" && !has(pg.Types, faq) && askImpr >= minSectionImpr {
|
|
out = append(out, Suggestion{
|
|
Key: "section:faq:" + pg.Path, Kind: "Add a FAQ", Title: pg.Path + " " + pg.Title,
|
|
Why: fmt.Sprintf("Google shows it %s times in 90 days for questions it doesn't answer in a FAQ: %s.", seo.Thousands(askImpr), quoteList(asks, 3)),
|
|
Score: sectionScore(askImpr, rate),
|
|
Action: link(faq, "Answer the questions people search for this page: "+strings.Join(asks[:min(5, len(asks))], "; ")),
|
|
})
|
|
}
|
|
if table != "" && !has(pg.Types, table) && vsImpr >= minSectionImpr {
|
|
out = append(out, Suggestion{
|
|
Key: "section:table:" + pg.Path, Kind: "Add a comparison", Title: pg.Path + " " + pg.Title,
|
|
Why: fmt.Sprintf("Google shows it %s times in 90 days for searches that compare: %s.", seo.Thousands(vsImpr), quoteList(vs, 3)),
|
|
Score: sectionScore(vsImpr, rate),
|
|
Action: link(table, "Compare, for the searches that bring people here: "+strings.Join(vs[:min(5, len(vs))], "; ")+". Say only what the Market and the profile say."),
|
|
})
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
// sectionScore guesses a section's worth: a few more clicks on the
|
|
// searches it answers (2% of their impressions), times the sign-up rate.
|
|
func sectionScore(impr int, rate float64) float64 {
|
|
if rate == 0 {
|
|
return float64(impr) / 20000
|
|
}
|
|
return float64(impr) * 0.02 * rate
|
|
}
|
|
|
|
func firstOf(have []string, want ...string) string {
|
|
for _, w := range want {
|
|
if slices.Contains(have, w) {
|
|
return w
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func quoteList(qs []string, n int) string {
|
|
var out []string
|
|
for i, q := range qs {
|
|
if i == n {
|
|
out = append(out, "…")
|
|
break
|
|
}
|
|
out = append(out, "“"+q+"”")
|
|
}
|
|
return strings.Join(out, ", ")
|
|
}
|