From 855615ae7f099982d06fbfcfab9ee4c50d99ded3 Mon Sep 17 00:00:00 2001 From: David Young Date: Tue, 24 Nov 2026 07:13:38 -0700 Subject: [PATCH] Phase 7 part 3: suggestions from the funnel MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- internal/next/next.go | 342 ++++++++++++++++++++++++ internal/next/next_test.go | 79 ++++++ internal/web/sitepages.go | 3 + internal/web/templates/sites-pages.html | 8 +- 4 files changed, 428 insertions(+), 4 deletions(-) create mode 100644 internal/next/next.go create mode 100644 internal/next/next_test.go diff --git a/internal/next/next.go b/internal/next/next.go new file mode 100644 index 0000000..3fdee5c --- /dev/null +++ b/internal/next/next.go @@ -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¬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 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" + } +} diff --git a/internal/next/next_test.go b/internal/next/next_test.go new file mode 100644 index 0000000..fa2ba47 --- /dev/null +++ b/internal/next/next_test.go @@ -0,0 +1,79 @@ +package next + +import ( + "path/filepath" + "strings" + "testing" + "time" + + "supermarket/internal/db" + "supermarket/internal/profile" + "supermarket/internal/prospects" + "supermarket/internal/signals" +) + +var now = time.Date(2026, 11, 24, 9, 0, 0, 0, time.UTC) + +func openDB(t *testing.T) *db.DB { + t.Helper() + d, err := db.Open(filepath.Join(t.TempDir(), "app.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { d.Close() }) + return d +} + +func TestSignalsWithoutPages(t *testing.T) { + d := openDB(t) + edu := &signals.Signal{Name: "Education", Status: "testing"} + quiet := &signals.Signal{Name: "Quiet", Status: "testing"} + signals.Save(d, edu) + signals.Save(d, quiet) + for i, stage := range []string{signals.StageReplied, signals.StageReplied, signals.StageInterested} { + if _, err := signals.Record(d, signals.Event{SignalID: edu.ID, Stage: stage, Channel: "explee", Source: "explee", + Subject: "explee:" + string(rune('a'+i)), ExternalID: stage + string(rune('a'+i)), At: now.AddDate(0, 0, -3)}); err != nil { + t.Fatal(err) + } + } + got, err := SignalsWithoutPages(d, now) + if err != nil { + t.Fatal(err) + } + if len(got) != 1 || got[0].Title != "Education" || !strings.Contains(got[0].Why, "2 replies and 1 interested person") || + !strings.Contains(got[0].Action.URL, "kind=landing&signal=") { + t.Errorf("got %+v", got) + } +} + +func TestAppsInReplies(t *testing.T) { + d := openDB(t) + for i, text := range []string{ + "origami.chat campaign “CRM buyers on Salesforce”: We moved our help desk to FreeScout last year and love it.", + "origami.chat campaign “Ministries”: Do you host Planning Center? We also use freescout.", + "explee.com campaign “Startups”: Runs Slack and Planning Center for 40 staff.", + "explee.com campaign “Startups”: nothing useful here", + } { + if _, _, err := prospects.AddContact(d, prospects.Contact{FirstName: "P", LastName: string(rune('a' + i)), Email: string(rune('a'+i)) + "@x.example", + Source: prospects.SourceManual, SourceDetail: text}, now); err != nil { + t.Fatal(err) + } + } + p := &profile.Profile{} + p.Targets.Technologies = []string{"Planning Center", "Slack"} + // The site has a FreeScout page; Salesforce is only in a campaign's name. + ms, err := AppsInReplies(d, p, []string{"/freescout/", "/pricing/"}, []string{"Pricing"}) + if err != nil { + t.Fatal(err) + } + if len(ms) != 1 || ms[0].Name != "Planning Center" || ms[0].People != 2 { + t.Fatalf("mentions: %+v", ms) + } + s := MentionSuggestions(ms, p) + if s[0].Kind != "Alternative page" || !strings.Contains(s[0].Why, "2 people named it") { + t.Errorf("suggestion: %+v", s[0]) + } + if !hasPage("FreeScout", nil, []string{"FreeScout — help desk you own"}) || hasPage("Plane", []string{"/planning-center/"}, nil) { + t.Error("hasPage") + } +} diff --git a/internal/web/sitepages.go b/internal/web/sitepages.go index 0b46e64..2b33003 100644 --- a/internal/web/sitepages.go +++ b/internal/web/sitepages.go @@ -149,6 +149,9 @@ func (s *Server) sitePagesPage(w http.ResponseWriter, r *http.Request) { func (s *Server) renderSitePages(w http.ResponseWriter, r *http.Request, errMsg string) { all, cur := s.currentSite(r) data := map[string]any{"Sites": all, "Current": cur, "Kinds": sites.Kinds, "Gitea": s.gitea() != nil} + // A suggestion (SEO → Next) can fill the form in: kind, signal, notes. + q := r.URL.Query() + data["Pre"] = map[string]string{"Kind": q.Get("kind"), "Signal": q.Get("signal"), "Notes": q.Get("notes")} if cur != nil && cur.Repo != "" { ps, err := sites.Pages(s.DB, cur.URL) if err != nil { diff --git a/internal/web/templates/sites-pages.html b/internal/web/templates/sites-pages.html index 7f52658..1b559e0 100644 --- a/internal/web/templates/sites-pages.html +++ b/internal/web/templates/sites-pages.html @@ -10,14 +10,14 @@ {{if .Err}}

{{.URL}}: {{.Err}}. Set it under Settings → Profile.

{{else}} -
+

A new page

{{if not $d.AI}}

Building pages needs the AI: choose a provider under Settings → AI.

{{end}} {{if not $d.Gitea}}

Supermarket reads the site with your Gitea token: save one under Settings → Search engines.

{{end}}
@@ -31,13 +31,13 @@
- +