Files
supermarket/internal/web/next.go
T
davidandClaude Opus 5.5 a1409d91ad Phase 8 part 3: lost links
Each known linking page (from Bing, Plausible or added by hand) is
opened once a week, at most 100 a day, to check it still links to the
site: kept, gone (the page no longer has the link), page gone (404, 410
or moved elsewhere) or pointing at a 404 (our page it links to is gone).
SEO → Links lists the lost ones with what happened, when last seen and
what the site brought; links can be added by hand (checked at once),
checked now, or forgotten. What to write next suggests a redirect for a
link to a 404, and asking for a lost link back when it brought visitors.
Links and What to write next now work for websites without Search
Console too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 08:43:30 -07:00

262 lines
8.0 KiB
Go

package web
import (
"context"
"fmt"
"net/http"
"slices"
"strconv"
"strings"
"time"
"supermarket/internal/backlinks"
"supermarket/internal/inventory"
"supermarket/internal/next"
"supermarket/internal/profile"
"supermarket/internal/seo"
"supermarket/internal/tracking"
)
// What to write next (SEO → What to write next): SEO's suggestions and the
// funnel's in one list, ranked by the sign-ups they're expected to bring.
const (
maxNext = 10
nextDismissed = "next:dismissed" // suggestion key → when it was dismissed
dismissFor = 90 * 24 * time.Hour
)
// nextFor works out a website's list, without the dismissed suggestions;
// more is how many fell below the first maxNext.
func (s *Server) nextFor(cur seoSite, now time.Time) (list []next.Suggestion, more int, err error) {
var all []next.Suggestion
site := strconv.Itoa(cur.Index)
// SEO: the pages that would gain most from new wording (Push pages and
// the audit's title and description issues), by expected sign-ups.
if cur.Property != "" {
conv := s.seoConv(cur.URL)
cands, err := seo.Candidates(s.DB, auditKey(cur), cur.Property, conv, now)
if err != nil {
return nil, 0, err
}
for _, c := range cands {
what, kind := "", "New title and description"
switch {
case c.Title && !c.Desc:
what, kind = "title", "New title"
case c.Desc && !c.Title:
what, kind = "description", "New description"
}
score := c.Expected
if conv == nil || score == 0 {
// Without conversion data, by how often Google shows it.
score = float64(c.Traffic.Impressions) / 20000
}
all = append(all, next.Suggestion{
Key: "change:" + seo.PathKey(c.Page), Kind: kind, Title: pagePath(c.Page), Why: c.Why, Score: score,
Action: next.Action{Label: "Propose new wording", Method: "POST", URL: "/seo/changes/page?site=" + site, Busy: "Writing…",
Fields: map[string]string{"page": c.Page, "why": c.Why, "what": what}},
})
}
}
// The funnel: signals without a landing page, apps people name.
sigs, err := next.SignalsWithoutPages(s.DB, now)
if err != nil {
return nil, 0, err
}
all = append(all, sigs...)
if p, _ := profile.Load(s.DB); p != nil {
var paths, titles []string
if a, _ := seo.LatestAudit(s.DB, cur.URL); a != nil {
for _, pg := range a.Pages {
paths = append(paths, seo.PathKey(pg.URL))
titles = append(titles, pg.Title)
}
}
if len(paths) > 0 { // without the site's pages, any app would look missing
ms, err := next.AppsInReplies(s.DB, p, paths, titles)
if err != nil {
return nil, 0, err
}
all = append(all, next.MentionSuggestions(ms, p)...)
}
}
// Sections for pages already on the site, from what they're searched for.
if cur.Property != "" {
if ideas, err := s.sectionIdeas(cur); err == nil {
all = append(all, ideas...)
}
}
all = append(all, s.lostLinkIdeas(cur)...)
stalled, err := next.Stalled(s.DB, cur.URL, cur.Index, now)
if err != nil {
return nil, 0, err
}
all = append(all, stalled...)
// Not the dismissed ones; the most promising first.
var dismissed map[string]time.Time
_, _ = s.DB.GetJSON(nextDismissed, &dismissed)
seen := map[string]bool{}
for _, sg := range all {
if at, ok := dismissed[sg.Key]; (ok && now.Sub(at) < dismissFor) || seen[sg.Key] {
continue
}
seen[sg.Key] = true
list = append(list, sg)
}
slices.SortStableFunc(list, func(a, b next.Suggestion) int {
switch {
case a.Score > b.Score:
return -1
case a.Score < b.Score:
return 1
}
return strings.Compare(a.Key, b.Key)
})
if len(list) > maxNext {
more = len(list) - maxNext
list = list[:maxNext]
}
return list, more, nil
}
func (s *Server) seoNextPage(w http.ResponseWriter, r *http.Request) {
// Every website with an address: only some suggestions need Search
// Console, and those are skipped without it.
sites, cur := s.auditSites(r)
data := map[string]any{"Sites": sites, "Current": cur, "Connected": true}
data["Path"] = "/seo/next"
if cur != nil {
list, more, err := s.nextFor(*cur, time.Now())
if err != nil {
s.serverError(w, err)
return
}
data["Next"], data["More"] = list, more
data["HasConv"] = s.seoConv(cur.URL) != nil
}
s.render(w, r, "seo-next", page{Title: "What to write next", Nav: "seo/next", Data: data})
}
// seoNextDismiss hides a suggestion for 90 days.
func (s *Server) seoNextDismiss(w http.ResponseWriter, r *http.Request) {
key := strings.TrimSpace(r.PostFormValue("key"))
if key == "" || len(key) > 300 {
http.Error(w, "no suggestion", http.StatusBadRequest)
return
}
var dismissed map[string]time.Time
_, _ = s.DB.GetJSON(nextDismissed, &dismissed)
if dismissed == nil {
dismissed = map[string]time.Time{}
}
now := time.Now()
for k, at := range dismissed { // forget the ones that came back anyway
if now.Sub(at) > dismissFor {
delete(dismissed, k)
}
}
dismissed[key] = now
if err := s.DB.PutJSON(nextDismissed, dismissed); err != nil {
s.serverError(w, err)
return
}
idx, _ := strconv.Atoi(r.URL.Query().Get("site"))
redirect(w, r, "/seo/next?site="+strconv.Itoa(idx), "next-dismissed")
}
// sectionIdeas suggest a FAQ or a comparison for the site's section pages,
// from the searches that bring people to them.
func (s *Server) sectionIdeas(cur seoSite) ([]next.Suggestion, error) {
var repo *siteRepo
for _, sr := range s.siteRepos() {
if sr.URL == cur.URL && sr.Repo != "" {
r := sr
repo = &r
}
}
if repo == nil {
return nil, nil
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
cat, err := s.catalog(ctx, *repo, false)
if err != nil {
return nil, err
}
var pages []next.SectionPage
for _, pg := range cat.Pages {
if pg.Sections && !pg.Draft {
pages = append(pages, next.SectionPage{Path: pg.Path, Title: pg.Title, Types: pg.Types})
}
}
var types []string
for _, t := range cat.Types {
if !t.Missing {
types = append(types, t.Name)
}
}
sc := s.scope(cur)
searches, err := seo.SearchesByPath(s.DB, sc)
if err != nil {
return nil, err
}
var competitors []string
if entries, err := inventory.List(s.DB, "competitor"); err == nil {
for _, e := range entries {
competitors = append(competitors, e.Name)
}
}
if p, _ := profile.Load(s.DB); p != nil {
competitors = append(competitors, p.Targets.Technologies...)
}
rate, _ := sc.Rate("")
return next.SectionIdeas(pages, searches, types, competitors, cur.Index, rate), nil
}
// lostLinkIdeas suggest fixing links lost or pointing at a 404: a redirect
// for the second, a word with the linking site for the first when it
// brought visitors.
func (s *Server) lostLinkIdeas(cur seoSite) []next.Suggestion {
links, err := backlinks.Links(s.DB, cur.URL)
if err != nil {
return nil
}
brought := map[string]tracking.Referrer{}
if p, _ := profile.Load(s.DB); p != nil {
for _, w := range p.Websites {
if w.URL == cur.URL {
list, _, _ := tracking.Referrers(s.DB, w, linkDays)
for _, ref := range list {
brought[strings.TrimPrefix(strings.ToLower(ref.Source), "www.")] = ref
}
}
}
}
rate, _ := s.scope(cur).Rate("")
var out []next.Suggestion
for _, l := range links {
b := brought[l.Host()]
worth := float64(b.Signups) + float64(b.Visitors)*rate
see := next.Action{Label: "See the link", Method: "GET", URL: "/seo/links?site=" + strconv.Itoa(cur.Index) + "#lost"}
visits := ""
if b.Visitors > 0 {
visits = fmt.Sprintf(" It brought %d visitors in 90 days.", b.Visitors)
}
switch {
case l.Status == backlinks.StatusTarget404:
out = append(out, next.Suggestion{Key: "link-404:" + l.Target, Kind: "Fix with a redirect", Title: l.Target,
Why: l.Host() + " links to " + l.Target + ", which answers 404: redirect it to where the page went, and the link works again." + visits,
Score: 0.3 + worth, Action: see})
case l.Lost() && b.Visitors > 0:
out = append(out, next.Suggestion{Key: "link-lost:" + l.Source, Kind: "Ask for the link back", Title: l.Host(),
Why: l.Note + visits + " A short note to the site often gets it back.",
Score: worth, Action: next.Action{Label: "Open their page", Method: "GET", URL: l.Source}})
}
}
return out
}