Files
supermarket/internal/seo/check.go
T
davidandClaude Opus 5.5 c36f786ae9 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>
2026-11-24 06:31:42 -07:00

365 lines
12 KiB
Go

package seo
import (
"fmt"
"math"
"slices"
"time"
"supermarket/internal/db"
)
// Settings are the thresholds that decide what's a real move, and whether
// the Monday report is emailed.
type Settings struct {
MinClicks int `json:"min_clicks"` // a move of more than this many clicks
MinPositions float64 `json:"min_positions"` // or of more than this many positions…
MinImpressions int `json:"min_impressions"` // …on at least this many impressions
EmailReport bool `json:"email_report"`
}
// DefaultSettings: the post's thresholds, with impressions raised to 300 as
// it advises for a small site.
var DefaultSettings = Settings{MinClicks: 5, MinPositions: 3, MinImpressions: 300}
const settingsKey = "seo:settings"
// LoadSettings returns the saved settings, or the defaults.
func LoadSettings(d *db.DB) Settings {
s := DefaultSettings
if ok, err := d.GetJSON(settingsKey, &s); err != nil || !ok {
return DefaultSettings
}
return s
}
// SaveSettings stores the settings.
func SaveSettings(d *db.DB, s Settings) error {
if s.MinClicks < 0 || s.MinPositions < 0 || s.MinImpressions < 0 {
return fmt.Errorf("thresholds can't be negative")
}
return d.PutJSON(settingsKey, s)
}
// Move is a page or a query whose numbers changed past the thresholds,
// last week against the week before.
type Move struct {
Kind string // page or query
Key string // the page's address, or the query
Before, After Numbers
NoData bool // no row this week: not a drop to zero, Google returned nothing
New bool // no row the week before
Why []string // what the data shows about the cause
}
// ClickDelta is the change in clicks.
func (m Move) ClickDelta() int { return m.After.Clicks - m.Before.Clicks }
// PosDelta is the change in position; negative is better.
func (m Move) PosDelta() float64 {
if m.Before.Impressions == 0 || m.After.Impressions == 0 {
return 0
}
return m.After.Position - m.Before.Position
}
// Check is the morning check: the last 7 days of final data against the 7
// before.
type Check struct {
Site string
From, To string // this week
PrevFrom, PrevTo string // the week before
Before, After Numbers
Moves []Move
Settings Settings
Pages, Queries, Total int // how many pages and queries were compared
}
// Quiet reports that nothing real moved.
func (c *Check) Quiet() bool { return len(c.Moves) == 0 }
// weeks are the last 7 days up to the latest stored day, and the 7 before.
func weeks(d *db.DB, site string) (from, to, prevFrom, prevTo string, ok bool) {
to = Through(d, site)
t, err := time.Parse(dayFormat, to)
if to == "" || err != nil {
return "", "", "", "", false
}
return t.AddDate(0, 0, -6).Format(dayFormat), to, t.AddDate(0, 0, -13).Format(dayFormat), t.AddDate(0, 0, -7).Format(dayFormat), true
}
// 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
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
}
// grouped sums rows by a key: page, query, or a page's queries.
func grouped(d *db.DB, query string, args ...any) (map[string]Numbers, error) {
rows, err := d.Query(query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
out := map[string]Numbers{}
for rows.Next() {
var k string
var n Numbers
var ps float64
if err := rows.Scan(&k, &n.Clicks, &n.Impressions, &ps); err != nil {
return nil, err
}
n.Position = position(ps, n.Impressions)
out[k] = n
}
return out, rows.Err()
}
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 `+cond+` AND date BETWEEN ? AND ? GROUP BY page`, append(args, from, to)...)
}
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 `+cond+` AND date BETWEEN ? AND ? GROUP BY query`, append(args, from, to)...)
}
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`, sc.Property, page, from, to)
}
func (s Settings) real(before, after Numbers) bool {
if abs(after.Clicks-before.Clicks) > s.MinClicks {
return true
}
// New this week, and already shown a lot.
if before.Impressions == 0 && after.Impressions >= max(s.MinImpressions, 1) {
return true
}
if before.Impressions > 0 && after.Impressions > 0 && max(before.Impressions, after.Impressions) >= s.MinImpressions &&
math.Abs(after.Position-before.Position) > s.MinPositions {
return true
}
return false
}
// vanished decides whether a page or query that has no row this week is
// worth saying so: it was big enough to have passed a threshold.
func (s Settings) vanished(before Numbers) bool {
return before.Clicks > s.MinClicks || before.Impressions >= s.MinImpressions
}
func abs(n int) int {
if n < 0 {
return -n
}
return n
}
// 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, sc Scope, set Settings) (*Check, error) {
from, to, pfrom, pto, ok := weeks(d, sc.Property)
if !ok {
return nil, nil
}
c := &Check{Site: sc.Property, From: from, To: to, PrevFrom: pfrom, PrevTo: pto, Settings: set}
var err error
if c.After, err = siteNumbers(d, sc, from, to); err != nil {
return nil, err
}
if c.Before, err = siteNumbers(d, sc, pfrom, pto); err != nil {
return nil, err
}
for _, kind := range []string{"page", "query"} {
load := pagesIn
if kind == "query" {
load = queriesIn
}
after, err := load(d, sc, from, to)
if err != nil {
return nil, err
}
before, err := load(d, sc, pfrom, pto)
if err != nil {
return nil, err
}
keys := map[string]bool{}
for k := range after {
keys[k] = true
}
for k := range before {
keys[k] = true
}
if kind == "page" {
c.Pages = len(keys)
} else {
c.Queries = len(keys)
}
for k := range keys {
a, hasA := after[k]
b, hasB := before[k]
m := Move{Kind: kind, Key: k, Before: b, After: a, NoData: !hasA, New: !hasB}
switch {
case !hasA:
if !set.vanished(b) {
continue
}
m.Why = append(m.Why, "Search Console returned no row for it this week: no data, not a drop to zero.")
case !set.real(b, a):
continue
case !hasB:
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, sc, &m, from, to, pfrom, pto, set); err != nil {
return nil, err
}
}
c.Moves = append(c.Moves, m)
}
}
slices.SortStableFunc(c.Moves, func(x, y Move) int {
if dx, dy := abs(x.ClickDelta()), abs(y.ClickDelta()); dx != dy {
return dy - dx
}
wx := math.Abs(x.PosDelta()) * float64(max(x.Before.Impressions, x.After.Impressions))
wy := math.Abs(y.PosDelta()) * float64(max(y.Before.Impressions, y.After.Impressions))
switch {
case wx > wy:
return -1
case wx < wy:
return 1
}
if x.Kind != y.Kind {
if x.Kind == "page" {
return -1
}
return 1
}
if x.Key < y.Key {
return -1
}
return 1
})
return c, nil
}
// 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, 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, sc, m.Key, pfrom, pto)
if err != nil {
return err
}
if len(after)+len(before) == 0 {
m.Why = append(m.Why, "Google names none of the searches it was shown for, so there's no cause to read.")
return nil
}
// The query whose clicks changed most.
if dc := m.ClickDelta(); dc != 0 {
best, bestD := "", 0
for q := range union(after, before) {
if delta := after[q].Clicks - before[q].Clicks; abs(delta) > abs(bestD) || (abs(delta) == abs(bestD) && delta != 0 && q < best) {
best, bestD = q, delta
}
}
if best != "" && bestD*dc > 0 {
m.Why = append(m.Why, fmt.Sprintf("“%s”: %s.", best, change(before[best], after[best])))
}
}
if math.Abs(m.PosDelta()) <= set.MinPositions {
return nil
}
// Like for like: the searches it had both weeks, weighted by this week's
// impressions.
var w, moved float64
for q, a := range after {
if b, ok := before[q]; ok && a.Impressions > 0 && b.Impressions > 0 {
w += float64(a.Impressions)
moved += float64(a.Impressions) * (a.Position - b.Position)
}
}
// The query whose impressions changed most.
shift, shiftD := "", 0
for q := range union(after, before) {
if delta := after[q].Impressions - before[q].Impressions; abs(delta) > abs(shiftD) || (abs(delta) == abs(shiftD) && delta != 0 && q < shift) {
shift, shiftD = q, delta
}
}
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 %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 %s: its rankings changed, not just the mix of searches.", places(like)))
return nil
}
if shift != "" {
m.Why = append(m.Why, fmt.Sprintf("It was shown for different searches each week; biggest change: “%s”, %s.", shift, change(before[shift], after[shift])))
}
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 {
out[k] = true
}
for k := range b {
out[k] = true
}
return out
}
// change describes a query's numbers from one week to the next.
func change(b, a Numbers) string {
switch {
case b.Impressions == 0:
return fmt.Sprintf("new this week, %s impressions at position %.1f, %s %s", Thousands(a.Impressions), a.Position, Thousands(a.Clicks), plural(a.Clicks, "click", "clicks"))
case a.Impressions == 0:
return fmt.Sprintf("%s impressions at position %.1f the week before, no data this week", Thousands(b.Impressions), b.Position)
}
return fmt.Sprintf("%s → %s clicks, %s → %s impressions, position %.1f → %.1f",
Thousands(b.Clicks), Thousands(a.Clicks), Thousands(b.Impressions), Thousands(a.Impressions), b.Position, a.Position)
}