Files
supermarket/internal/seo/check.go
T
davidandClaude Opus 5.5 aeba28b658 SEO: daily clicks chart, top searches, percentages, daily email
- The morning check draws clicks by day, this week over the week before.
- The morning check and the Monday report list the searches that gained
  and lost most clicks (any size; real moves stay on their own list).
- The week's clicks and impressions show their change in percent.
- Settings → Search engines can email the morning check, at most once a
  day, when something really moved. Both emails carry the new lists.
- With a domain property, a line says how many clicks went to its other
  hosts (a shop, a Gitea…) and for which search.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 06:55:54 -07:00

420 lines
14 KiB
Go

package seo
import (
"fmt"
"math"
"slices"
"strings"
"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"`
EmailCheck bool `json:"email_check"` // email the morning check when something really moved
}
// 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
Days, PrevDays []Day // clicks by day, this week and the week before
Gains, Losses []QueryChange // the searches whose clicks changed most, any size
Outside []Outside // clicks the property sent to its other hosts
}
// 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)
}
}
if c.Days, err = days(d, sc, from, to); err != nil {
return nil, err
}
if c.PrevDays, err = days(d, sc, pfrom, pto); err != nil {
return nil, err
}
qa, err := queriesIn(d, sc, from, to)
if err != nil {
return nil, err
}
qb, err := queriesIn(d, sc, pfrom, pto)
if err != nil {
return nil, err
}
c.Gains, c.Losses = topQueries(qb, qa, TopChanges)
if c.Outside, err = outside(d, sc, from, to); err != nil {
return nil, err
}
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)
}
// Text is the morning check as an email.
func (c *Check) Text(siteURL string) string {
var b strings.Builder
fmt.Fprintf(&b, "Morning check for %s: %s to %s, against %s to %s\n\n", siteURL, c.From, c.To, c.PrevFrom, c.PrevTo)
fmt.Fprintf(&b, "Clicks %s → %s%s\n", Thousands(c.Before.Clicks), Thousands(c.After.Clicks), inParens(Percent(c.Before.Clicks, c.After.Clicks)))
fmt.Fprintf(&b, "Impressions %s → %s%s\n", Thousands(c.Before.Impressions), Thousands(c.After.Impressions), inParens(Percent(c.Before.Impressions, c.After.Impressions)))
fmt.Fprintf(&b, "Position %.1f → %.1f\n", c.Before.Position, c.After.Position)
writeOutside(&b, c.Outside)
b.WriteString("\nWhat really moved\n")
if c.Quiet() {
b.WriteString(" Nothing.\n")
}
for _, m := range c.Moves {
what := m.Key
if m.Kind == "query" {
what = "search “" + m.Key + "”"
}
if m.NoData {
fmt.Fprintf(&b, " %s: no data this week (it had %d clicks)\n", what, m.Before.Clicks)
} else {
fmt.Fprintf(&b, " %s: %s\n", what, change(m.Before, m.After))
}
for _, w := range m.Why {
fmt.Fprintf(&b, " %s\n", w)
}
}
b.WriteString("\n")
writeChanges(&b, c.Gains, c.Losses)
return b.String()
}