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 } func siteNumbers(d *db.DB, site, 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) 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, site, from, to string) (map[string]Numbers, error) { 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) } func queriesIn(d *db.DB, site, 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 date BETWEEN ? AND ? GROUP BY query`, site, from, to) } func pageQueriesIn(d *db.DB, site, 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) } // 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 } // 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, site string, set Settings) (*Check, error) { from, to, pfrom, pto, ok := weeks(d, site) if !ok { return nil, nil } c := &Check{Site: site, From: from, To: to, PrevFrom: pfrom, PrevTo: pto, Settings: set} var err error if c.After, err = siteNumbers(d, site, from, to); err != nil { return nil, err } if c.Before, err = siteNumbers(d, site, pfrom, pto); err != nil { return nil, err } for _, kind := range []string{"page", "query"} { load := pagesIn if kind == "query" { load = queriesIn } after, err := load(d, site, from, to) if err != nil { return nil, err } before, err := load(d, site, 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, site, &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, site string, m *Move, from, to, pfrom, pto string, set Settings) error { after, err := pageQueriesIn(d, site, m.Key, from, to) if err != nil { return err } before, err := pageQueriesIn(d, site, 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 %+.1f positions, on the searches it had both weeks. The average moved because Google showed it for a different mix of searches.", 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)) 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 } 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) }