Fixes from the first round of TEST.md

SEO: a domain property (sc-domain:) covers every subdomain, so the shop,
Gitea and forum were counted as the website. What ranks, the morning
check, the Monday report, keywords, change candidates and the audit's
traffic now read only the website's own host (with or without www).
The report keeps pages worth a proposal apart from "Waiting for your
yes", explains only moves past the thresholds, and says "places up/down".

Also:
- Feed summaries drop the posts' scripts and styles.
- Spend you log can't be negative.
- Test and check buttons can't be clicked twice while they run.
- Previews show the site's web fonts and icon sprites.
- Backups are read without leaving -wal/-shm files; deleting one removes
  them, and leftovers are swept at start.
- The Overview's setup flags a CRM that Hermes can't reach.
- Import now says what came in; adding a prospect that exists says so;
  prospects can be deleted.
- Signal tags and brief addresses keep accented letters (Ü → u).
- Page errors start with a capital; clearer messages for bad uploads,
  CRM retry and cancel, keywords, and the finished audit.
- The module you're in stays unfolded in the sidebar.
- A picked keyword can be unpicked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-24 06:31:42 -07:00
co-authored by Claude Opus 5.5
parent 3ddf716e71
commit c36f786ae9
52 changed files with 796 additions and 128 deletions
+1 -1
View File
@@ -226,7 +226,7 @@ func RunAudit(ctx context.Context, d *db.DB, f *Fetcher, siteURL, property strin
traffic := map[string]Numbers{}
if property != "" {
if from, to, ok := period(d, property, RanksDays); ok {
if rows, err := pageNumbers(d, property, from, to); err == nil {
if rows, err := pageNumbers(d, NewScope(property, siteURL), from, to); err == nil {
for _, p := range rows {
traffic[normalize(p.Page)] = p.Numbers
}
+2 -5
View File
@@ -19,6 +19,7 @@ import (
"supermarket/internal/db"
"supermarket/internal/hugorepo"
"supermarket/internal/profile"
"supermarket/internal/slug"
)
// Brief statuses.
@@ -308,11 +309,7 @@ Answer with JSON only, in this shape:
return b, nil
}
var nonSlug = regexp.MustCompile(`[^a-z0-9]+`)
func slugify(s string) string {
return strings.Trim(nonSlug.ReplaceAllString(strings.ToLower(s), "-"), "-")
}
func slugify(s string) string { return slug.Make(s) }
// EditBrief saves the user's changes to a brief and their answers.
func EditBrief(d *db.DB, id int64, plan Plan, answers []string, pagePath string) error {
+1 -1
View File
@@ -248,7 +248,7 @@ func Candidates(d *db.DB, site, property string, now time.Time) ([]Candidate, er
out = append(out, c)
}
if property != "" {
if r, err := WhatRanks(d, property); err == nil && r != nil {
if r, err := WhatRanks(d, NewScope(property, site)); err == nil && r != nil {
for _, p := range r.Push {
add(Candidate{Page: p.Page, Why: p.Why, Title: true, Desc: true, Traffic: p.Numbers})
}
+1 -1
View File
@@ -116,7 +116,7 @@ func TestChangeLifecycle(t *testing.T) {
if _, err := pr.SuggestChanges(ctx, d, site, prop, time.Date(2026, 11, 1, 9, 0, 0, 0, time.UTC)); err == nil {
t.Error("proposed again for the same page")
}
if r, _ := Weekly(d, prop, time.Now()); r == nil || len(r.Waiting) != 1 || !strings.Contains(r.Waiting[0].Why, "New title: “Pricing and plans") {
if r, _ := Weekly(d, Scope{Property: prop}, time.Now()); r == nil || len(r.Waiting) != 1 || !strings.Contains(r.Waiting[0].Why, "New title: “Pricing and plans") {
t.Errorf("report's waiting list: %+v", r)
}
if err := EditChange(d, c.ID, "Pricing and plans from $5 · Site", c.NewDescription); err != nil {
+46 -23
View File
@@ -88,11 +88,20 @@ func weeks(d *db.DB, site string) (from, to, prevFrom, prevTo string, ok bool) {
return t.AddDate(0, 0, -6).Format(dayFormat), to, t.AddDate(0, 0, -13).Format(dayFormat), t.AddDate(0, 0, -7).Format(dayFormat), true
}
func siteNumbers(d *db.DB, site, from, to string) (Numbers, error) {
// siteNumbers are the scope's totals. A whole property has its own daily
// totals; a website within one is the sum of its pages.
func siteNumbers(d *db.DB, sc Scope, from, to string) (Numbers, error) {
var n Numbers
var ps float64
err := d.QueryRow(`SELECT coalesce(sum(clicks), 0), coalesce(sum(impressions), 0), coalesce(sum(pos_sum), 0)
FROM gsc_site_days WHERE site = ? AND date BETWEEN ? AND ?`, site, from, to).Scan(&n.Clicks, &n.Impressions, &ps)
var err error
if len(sc.Hosts) == 0 {
err = d.QueryRow(`SELECT coalesce(sum(clicks), 0), coalesce(sum(impressions), 0), coalesce(sum(pos_sum), 0)
FROM gsc_site_days WHERE site = ? AND date BETWEEN ? AND ?`, sc.Property, from, to).Scan(&n.Clicks, &n.Impressions, &ps)
} else {
cond, args := sc.where()
err = d.QueryRow(`SELECT coalesce(sum(clicks), 0), coalesce(sum(impressions), 0), coalesce(sum(pos_sum), 0)
FROM gsc_page_days WHERE `+cond+` AND date BETWEEN ? AND ?`, append(args, from, to)...).Scan(&n.Clicks, &n.Impressions, &ps)
}
n.Position = position(ps, n.Impressions)
return n, err
}
@@ -118,22 +127,23 @@ func grouped(d *db.DB, query string, args ...any) (map[string]Numbers, error) {
return out, rows.Err()
}
func pagesIn(d *db.DB, site, from, to string) (map[string]Numbers, error) {
func pagesIn(d *db.DB, sc Scope, from, to string) (map[string]Numbers, error) {
cond, args := sc.where()
return grouped(d, `SELECT page, sum(clicks), sum(impressions), sum(pos_sum) FROM gsc_page_days
WHERE site = ? AND date BETWEEN ? AND ? GROUP BY page`, site, from, to)
WHERE `+cond+` AND date BETWEEN ? AND ? GROUP BY page`, append(args, from, to)...)
}
func queriesIn(d *db.DB, site, from, to string) (map[string]Numbers, error) {
func queriesIn(d *db.DB, sc Scope, from, to string) (map[string]Numbers, error) {
cond, args := sc.where()
return grouped(d, `SELECT query, sum(clicks), sum(impressions), sum(pos_sum) FROM gsc_query_days
WHERE site = ? AND date BETWEEN ? AND ? GROUP BY query`, site, from, to)
WHERE `+cond+` AND date BETWEEN ? AND ? GROUP BY query`, append(args, from, to)...)
}
func pageQueriesIn(d *db.DB, site, page, from, to string) (map[string]Numbers, error) {
func pageQueriesIn(d *db.DB, sc Scope, page, from, to string) (map[string]Numbers, error) {
return grouped(d, `SELECT query, sum(clicks), sum(impressions), sum(pos_sum) FROM gsc_query_days
WHERE site = ? AND page = ? AND date BETWEEN ? AND ? GROUP BY query`, site, page, from, to)
WHERE site = ? AND page = ? AND date BETWEEN ? AND ? GROUP BY query`, sc.Property, page, from, to)
}
// real decides whether a change passes the thresholds.
func (s Settings) real(before, after Numbers) bool {
if abs(after.Clicks-before.Clicks) > s.MinClicks {
return true
@@ -165,17 +175,17 @@ func abs(n int) int {
// MorningCheck compares the last 7 days of final data with the 7 before,
// by page and by query, and keeps only real moves. It returns nil if there
// isn't two weeks of data yet.
func MorningCheck(d *db.DB, site string, set Settings) (*Check, error) {
from, to, pfrom, pto, ok := weeks(d, site)
func MorningCheck(d *db.DB, sc Scope, set Settings) (*Check, error) {
from, to, pfrom, pto, ok := weeks(d, sc.Property)
if !ok {
return nil, nil
}
c := &Check{Site: site, From: from, To: to, PrevFrom: pfrom, PrevTo: pto, Settings: set}
c := &Check{Site: sc.Property, From: from, To: to, PrevFrom: pfrom, PrevTo: pto, Settings: set}
var err error
if c.After, err = siteNumbers(d, site, from, to); err != nil {
if c.After, err = siteNumbers(d, sc, from, to); err != nil {
return nil, err
}
if c.Before, err = siteNumbers(d, site, pfrom, pto); err != nil {
if c.Before, err = siteNumbers(d, sc, pfrom, pto); err != nil {
return nil, err
}
for _, kind := range []string{"page", "query"} {
@@ -183,11 +193,11 @@ func MorningCheck(d *db.DB, site string, set Settings) (*Check, error) {
if kind == "query" {
load = queriesIn
}
after, err := load(d, site, from, to)
after, err := load(d, sc, from, to)
if err != nil {
return nil, err
}
before, err := load(d, site, pfrom, pto)
before, err := load(d, sc, pfrom, pto)
if err != nil {
return nil, err
}
@@ -219,7 +229,7 @@ func MorningCheck(d *db.DB, site string, set Settings) (*Check, error) {
m.Why = append(m.Why, "No row the week before: new in Search Console this week.")
}
if kind == "page" && hasA && hasB {
if err := explainPage(d, site, &m, from, to, pfrom, pto, set); err != nil {
if err := explainPage(d, sc, &m, from, to, pfrom, pto, set); err != nil {
return nil, err
}
}
@@ -255,12 +265,12 @@ func MorningCheck(d *db.DB, site string, set Settings) (*Check, error) {
// explainPage says what the page's queries show about its move: which
// query's clicks changed most, and whether a position change is real or
// comes from Google showing it for a different mix of searches.
func explainPage(d *db.DB, site string, m *Move, from, to, pfrom, pto string, set Settings) error {
after, err := pageQueriesIn(d, site, m.Key, from, to)
func explainPage(d *db.DB, sc Scope, m *Move, from, to, pfrom, pto string, set Settings) error {
after, err := pageQueriesIn(d, sc, m.Key, from, to)
if err != nil {
return err
}
before, err := pageQueriesIn(d, site, m.Key, pfrom, pto)
before, err := pageQueriesIn(d, sc, m.Key, pfrom, pto)
if err != nil {
return err
}
@@ -302,13 +312,13 @@ func explainPage(d *db.DB, site string, m *Move, from, to, pfrom, pto string, se
if w > 0 {
like := moved / w
if math.Abs(like) < math.Abs(m.PosDelta())/2 {
m.Why = append(m.Why, fmt.Sprintf("Like for like it moved %+.1f positions, on the searches it had both weeks. The average moved because Google showed it for a different mix of searches.", like))
m.Why = append(m.Why, fmt.Sprintf("Like for like it moved %s, on the searches it had both weeks. The average moved because Google showed it for a different mix of searches.", places(like)))
if shift != "" {
m.Why = append(m.Why, fmt.Sprintf("Biggest change: “%s”, %s.", shift, change(before[shift], after[shift])))
}
return nil
}
m.Why = append(m.Why, fmt.Sprintf("On the searches it had both weeks it moved %+.1f positions: a real move.", like))
m.Why = append(m.Why, fmt.Sprintf("On the searches it had both weeks it moved %s: its rankings changed, not just the mix of searches.", places(like)))
return nil
}
if shift != "" {
@@ -317,6 +327,19 @@ func explainPage(d *db.DB, site string, m *Move, from, to, pfrom, pto string, se
return nil
}
// places says a change in average position in words: a lower position
// number is higher up the results.
func places(delta float64) string {
switch {
case math.Abs(delta) < 0.05:
return "less than 0.1 places"
case delta < 0:
return fmt.Sprintf("%.1f places up", -delta)
default:
return fmt.Sprintf("%.1f places down", delta)
}
}
func union(a, b map[string]Numbers) map[string]bool {
out := map[string]bool{}
for k := range a {
+57 -4
View File
@@ -62,7 +62,7 @@ func TestMorningCheckAndReport(t *testing.T) {
})
d.PutJSON(throughKey(site), "2026-11-19")
c, err := MorningCheck(d, site, DefaultSettings)
c, err := MorningCheck(d, Scope{Property: site}, DefaultSettings)
if err != nil {
t.Fatal(err)
}
@@ -84,7 +84,7 @@ func TestMorningCheckAndReport(t *testing.T) {
// The "best" page lost 21 positions on paper, under one in reality.
b := moves["page:"+best]
why := strings.Join(b.Why, " ")
if b.PosDelta() < 20 || !strings.Contains(why, "Like for like it moved +0.3") ||
if b.PosDelta() < 20 || !strings.Contains(why, "Like for like it moved 0.3 places down") ||
!strings.Contains(why, "“whey price comparison”, 0 → 0 clicks, 515 → 34 impressions, position 3.0 → 3.9") {
t.Errorf("best: %+v %v", b, why)
}
@@ -100,12 +100,12 @@ func TestMorningCheckAndReport(t *testing.T) {
}
// Higher thresholds: quiet.
q, _ := MorningCheck(d, site, Settings{MinClicks: 50, MinPositions: 50, MinImpressions: 100000})
q, _ := MorningCheck(d, Scope{Property: site}, Settings{MinClicks: 50, MinPositions: 50, MinImpressions: 100000})
if !q.Quiet() {
t.Errorf("not quiet: %+v", q.Moves)
}
rep, err := Weekly(d, site, time.Date(2026, 11, 23, 8, 0, 0, 0, time.UTC))
rep, err := Weekly(d, Scope{Property: site}, time.Date(2026, 11, 23, 8, 0, 0, 0, time.UTC))
if err != nil {
t.Fatal(err)
}
@@ -148,3 +148,56 @@ func TestWhere(t *testing.T) {
}
}
}
// A domain property covers every subdomain; a website's scope keeps only
// its own host, with or without www.
func TestScopeKeepsTheWebsite(t *testing.T) {
d := openDB(t)
const site = "sc-domain:whey.example"
week(t, d, site, "2026-11-06", row{clicks: 1000, impr: 5000, pos: 5}, []row{
{"https://shop.whey.example/", "whey shop", 900, 1000, 1},
{"https://whey.example/best/", "best whey", 40, 2000, 6},
{"https://www.whey.example/", "whey", 60, 2000, 3},
})
week(t, d, site, "2026-11-13", row{clicks: 1000, impr: 5000, pos: 5}, []row{
{"https://shop.whey.example/", "whey shop", 900, 1000, 1},
{"https://whey.example/best/", "best whey", 40, 2000, 6},
{"https://www.whey.example/", "whey", 60, 2000, 3},
})
d.PutJSON(throughKey(site), "2026-11-19")
sc := NewScope(site, "https://whey.example")
r, err := WhatRanks(d, sc)
if err != nil || r == nil {
t.Fatal(r, err)
}
if r.Total.Clicks != 200 || r.Total.Impressions != 8000 {
t.Errorf("totals include another host: %+v", r.Total)
}
for _, p := range r.Pages {
if !sc.Has(p.Page) {
t.Errorf("page from another host: %s", p.Page)
}
}
if len(r.Pages) != 2 {
t.Errorf("pages: %+v", r.Pages)
}
c, err := MorningCheck(d, sc, DefaultSettings)
if err != nil || c == nil || c.After.Clicks != 100 || c.Pages != 2 || c.Queries != 2 {
t.Errorf("check: %+v %v", c, err)
}
if whole, _ := WhatRanks(d, Scope{Property: site}); whole == nil || whole.Total.Clicks != 2000 {
t.Errorf("whole property: %+v", whole)
}
if !sc.Has("https://www.whey.example/x") || sc.Has("https://shop.whey.example/") || sc.Has("https://whey.example.evil/") {
t.Error("Has")
}
}
func TestPlaces(t *testing.T) {
for in, want := range map[float64]string{-12.8: "12.8 places up", 0.3: "0.3 places down", 0.01: "less than 0.1 places"} {
if got := places(in); got != want {
t.Errorf("places(%v) = %q, want %q", in, got, want)
}
}
}
+4 -2
View File
@@ -166,12 +166,14 @@ func FindKeywords(ctx context.Context, d *db.DB, site, property string, p *profi
// answers them, below page two.
if property != "" {
if from, to, ok := period(d, property, RanksDays); ok {
cond, args := NewScope(property, site).where()
args = append([]any{from, to}, args...)
rows, err := d.Query(`SELECT query, sum(impressions), sum(pos_sum),
(SELECT page FROM gsc_query_days q2 WHERE q2.site = q.site AND q2.query = q.query AND q2.date BETWEEN ? AND ?
GROUP BY page ORDER BY sum(impressions) DESC LIMIT 1)
FROM gsc_query_days q WHERE site = ? AND date BETWEEN ? AND ? GROUP BY query
FROM gsc_query_days q WHERE `+cond+` AND date BETWEEN ? AND ? GROUP BY query
HAVING sum(impressions) >= 20 AND sum(pos_sum) / sum(impressions) > 20
ORDER BY sum(impressions) DESC LIMIT 200`, from, to, property, from, to)
ORDER BY sum(impressions) DESC LIMIT 200`, append(args, from, to)...)
if err != nil {
return 0, err
}
+15 -17
View File
@@ -92,30 +92,27 @@ func period(d *db.DB, site string, days int) (from, to string, ok bool) {
// WhatRanks works out job 1 for a property, over the last RanksDays days
// of final data. It returns nil if nothing is stored yet.
func WhatRanks(d *db.DB, site string) (*Ranks, error) {
from, to, ok := period(d, site, RanksDays)
func WhatRanks(d *db.DB, sc Scope) (*Ranks, error) {
from, to, ok := period(d, sc.Property, RanksDays)
if !ok {
return nil, nil
}
r := &Ranks{Site: site, From: from, To: to, Anonymous: -1}
var posSum float64
if err := d.QueryRow(`SELECT coalesce(sum(clicks), 0), coalesce(sum(impressions), 0), coalesce(sum(pos_sum), 0)
FROM gsc_site_days WHERE site = ? AND date BETWEEN ? AND ?`, site, from, to).
Scan(&r.Total.Clicks, &r.Total.Impressions, &posSum); err != nil {
r := &Ranks{Site: sc.Property, From: from, To: to, Anonymous: -1}
var err error
if r.Total, err = siteNumbers(d, sc, from, to); err != nil {
return nil, err
}
r.Total.Position = position(posSum, r.Total.Impressions)
cond, args := sc.where()
var named int
if err := d.QueryRow(`SELECT coalesce(sum(clicks), 0) FROM gsc_query_days WHERE site = ? AND date BETWEEN ? AND ?`,
site, from, to).Scan(&named); err != nil {
if err := d.QueryRow(`SELECT coalesce(sum(clicks), 0) FROM gsc_query_days WHERE `+cond+` AND date BETWEEN ? AND ?`,
append(args, from, to)...).Scan(&named); err != nil {
return nil, err
}
if r.Total.Clicks > 0 {
r.Anonymous = 100 * float64(r.Total.Clicks-min(named, r.Total.Clicks)) / float64(r.Total.Clicks)
}
pages, err := pageNumbers(d, site, from, to)
pages, err := pageNumbers(d, sc, from, to)
if err != nil {
return nil, err
}
@@ -127,9 +124,9 @@ func WhatRanks(d *db.DB, site string) (*Ranks, error) {
}
rows, err := d.Query(`SELECT query, sum(clicks), sum(impressions), sum(pos_sum) FROM gsc_query_days
WHERE site = ? AND date BETWEEN ? AND ? GROUP BY query
WHERE `+cond+` AND date BETWEEN ? AND ? GROUP BY query
HAVING sum(impressions) > 0 AND 100.0 * sum(clicks) / sum(impressions) < ?
ORDER BY sum(impressions) DESC LIMIT 10`, site, from, to, lowCTR)
ORDER BY sum(impressions) DESC LIMIT 10`, append(args, from, to, lowCTR)...)
if err != nil {
return nil, err
}
@@ -167,7 +164,7 @@ func WhatRanks(d *db.DB, site string) (*Ranks, error) {
break
}
pick := Pick{Page: p.Page, Numbers: p.Numbers}
if err := mainQuery(d, site, from, to, &pick); err != nil {
if err := mainQuery(d, sc.Property, from, to, &pick); err != nil {
return nil, err
}
pick.Why = fmt.Sprintf("Shown %s times at position %.1f, %s %s.", Thousands(p.Impressions), p.Position, Thousands(p.Clicks), plural(p.Clicks, "click", "clicks"))
@@ -180,9 +177,10 @@ func WhatRanks(d *db.DB, site string) (*Ranks, error) {
}
// pageNumbers are every page's numbers over a period, most clicks first.
func pageNumbers(d *db.DB, site, from, to string) ([]PageRow, error) {
func pageNumbers(d *db.DB, sc Scope, from, to string) ([]PageRow, error) {
cond, args := sc.where()
rows, err := d.Query(`SELECT page, sum(clicks), sum(impressions), sum(pos_sum) FROM gsc_page_days
WHERE site = ? AND date BETWEEN ? AND ? GROUP BY page ORDER BY sum(clicks) DESC, sum(impressions) DESC`, site, from, to)
WHERE `+cond+` AND date BETWEEN ? AND ? GROUP BY page ORDER BY sum(clicks) DESC, sum(impressions) DESC`, append(args, from, to)...)
if err != nil {
return nil, err
}
+19 -8
View File
@@ -24,16 +24,18 @@ type Report struct {
Where string `json:"where"` // where the change came from, in a sentence
Pages []Move `json:"pages"` // the 3 pages that moved most
Waiting []Pick `json:"waiting"`
// Candidates are the pages worth a proposal, when none is waiting.
Candidates []Pick `json:"candidates,omitempty"`
}
// Weekly builds the Monday report for the latest week of final data. The
// "waiting for your yes" list holds at most 3 items.
func Weekly(d *db.DB, site string, now time.Time) (*Report, error) {
c, err := MorningCheck(d, site, Settings{}) // every change, to rank the pages
func Weekly(d *db.DB, sc Scope, now time.Time) (*Report, error) {
c, err := MorningCheck(d, sc, Settings{}) // every change, to rank the pages
if err != nil || c == nil {
return nil, err
}
r := &Report{Site: site, WeekFrom: c.From, WeekTo: c.To, CreatedAt: now, Before: c.Before, After: c.After}
r := &Report{Site: sc.Property, WeekFrom: c.From, WeekTo: c.To, CreatedAt: now, Before: c.Before, After: c.After}
r.Where = where(c.Before, c.After)
var pages []Move
for _, m := range c.Moves {
@@ -59,11 +61,12 @@ func Weekly(d *db.DB, site string, now time.Time) (*Report, error) {
pages = pages[:3]
}
// The causes, from the full check (which explains only real moves).
full, err := MorningCheck(d, site, LoadSettings(d))
full, err := MorningCheck(d, sc, LoadSettings(d))
if err != nil {
return nil, err
}
for i := range pages {
pages[i].Why = []string{"Under the thresholds for a real move: noise until it lasts."}
for _, m := range full.Moves {
if m.Kind == "page" && m.Key == pages[i].Key {
pages[i].Why = m.Why
@@ -73,7 +76,7 @@ func Weekly(d *db.DB, site string, now time.Time) (*Report, error) {
r.Pages = pages
// The changes proposed for the site, or else the pages to push.
rows, err := d.Query(`SELECT `+changeCols+` FROM seo_changes WHERE property = ? AND status = ? ORDER BY id LIMIT ?`,
site, ChangeProposed, MaxWaiting)
sc.Property, ChangeProposed, MaxWaiting)
if err != nil {
return nil, err
}
@@ -91,13 +94,15 @@ func Weekly(d *db.DB, site string, now time.Time) (*Report, error) {
}
r.Waiting = append(r.Waiting, Pick{Page: c.Page, Why: strings.Join(what, " ") + " Why: " + c.Why})
}
// With nothing proposed, the pages worth a proposal, kept apart: they
// aren't waiting for a yes until a change is proposed for them.
if len(r.Waiting) == 0 {
ranks, err := WhatRanks(d, site)
ranks, err := WhatRanks(d, sc)
if err != nil {
return nil, err
}
if ranks != nil {
r.Waiting = ranks.Push
r.Candidates = ranks.Push
}
}
return r, nil
@@ -212,10 +217,16 @@ func (r *Report) Text() string {
}
b.WriteString("\n3. Waiting for your yes\n")
if len(r.Waiting) == 0 {
b.WriteString(" Nothing this week.\n")
b.WriteString(" Nothing is waiting: no change has been proposed.\n")
}
for i, p := range r.Waiting {
fmt.Fprintf(&b, " %d. %s\n %s\n", i+1, p.Page, p.Why)
}
if len(r.Candidates) > 0 {
b.WriteString("\n Worth a proposal (Propose changes, on SEO → Changes):\n")
for _, p := range r.Candidates {
fmt.Fprintf(&b, " - %s\n %s\n", p.Page, p.Why)
}
}
return b.String()
}
+73
View File
@@ -0,0 +1,73 @@
package seo
import (
"net/url"
"strings"
)
// Scope is one website's share of a Search Console property. A domain
// property (sc-domain:example.com) covers every subdomain — a shop, a Gitea,
// a forum — so its rows are narrowed to the website's own host, with or
// without www. With no hosts it's the whole property.
type Scope struct {
Property string
Hosts []string // lower case, without www.
}
// NewScope is the scope of the website at siteURL within property. Only a
// domain property is narrowed, and only to a host within its domain: a
// URL-prefix property is one site already.
func NewScope(property, siteURL string) Scope {
s := Scope{Property: property}
domain, ok := strings.CutPrefix(strings.ToLower(property), "sc-domain:")
u, err := url.Parse(siteURL)
if !ok || err != nil {
return s
}
host := strings.TrimPrefix(strings.ToLower(u.Hostname()), "www.")
if host == domain || strings.HasSuffix(host, "."+domain) {
s.Hosts = []string{host}
}
return s
}
// Has says whether a page's address is on the website.
func (s Scope) Has(page string) bool {
if len(s.Hosts) == 0 {
return true
}
u, err := url.Parse(page)
if err != nil {
return false
}
h := strings.TrimPrefix(strings.ToLower(u.Hostname()), "www.")
for _, want := range s.Hosts {
if h == want {
return true
}
}
return false
}
// where is the SQL condition for the scope's rows of a gsc_ table, which
// has site and page columns, and its arguments.
func (s Scope) where() (string, []any) {
cond := "site = ?"
args := []any{s.Property}
if len(s.Hosts) == 0 {
return cond, args
}
var ors []string
for _, h := range s.Hosts {
h = likeEscape(h)
for _, prefix := range []string{"https://", "http://", "https://www.", "http://www."} {
ors = append(ors, `page LIKE ? ESCAPE '\'`, `page = ?`)
args = append(args, prefix+h+"/%", prefix+h)
}
}
return cond + " AND (" + strings.Join(ors, " OR ") + ")", args
}
func likeEscape(s string) string {
return strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(s)
}
+2 -2
View File
@@ -86,7 +86,7 @@ func TestSyncAndWhatRanks(t *testing.T) {
if err != nil || len(sites) != 1 || sites[0].URL != "sc-domain:whey.example" {
t.Fatalf("sites: %+v %v", sites, err)
}
if r, _ := WhatRanks(d, "sc-domain:whey.example"); r != nil {
if r, _ := WhatRanks(d, Scope{Property: "sc-domain:whey.example"}); r != nil {
t.Error("ranks before any data")
}
res, err := Sync(context.Background(), d, c, "sc-domain:whey.example", now)
@@ -106,7 +106,7 @@ func TestSyncAndWhatRanks(t *testing.T) {
t.Errorf("last sync: %+v", last)
}
r, err := WhatRanks(d, "sc-domain:whey.example")
r, err := WhatRanks(d, Scope{Property: "sc-domain:whey.example"})
if err != nil {
t.Fatal(err)
}