Phase 3 part 2: the morning check and the Monday report
The morning check compares the last 7 days of final Search Console data with the 7 before, by page and by search, and lists only moves past the thresholds (editable). Each move is explained from the data: the search whose clicks changed, and whether a position change is real or a change in the mix of searches. Missing rows are "no data", not zero. The Monday report has three numbers with where the change came from, the 3 pages that moved most, and "Waiting for your yes"; it's written each Monday, kept, and optionally emailed through the outreach mailbox. Schema 13. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,341 @@
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package seo
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/db"
|
||||
)
|
||||
|
||||
// put stores a week of data spread over its 7 days.
|
||||
type row struct {
|
||||
page, query string
|
||||
clicks, impr int
|
||||
pos float64
|
||||
}
|
||||
|
||||
func week(t *testing.T, d *db.DB, site, from string, site_ row, rows []row) {
|
||||
t.Helper()
|
||||
start, _ := time.Parse(dayFormat, from)
|
||||
// One day carries the week, which is enough for weekly sums.
|
||||
day := start.Format(dayFormat)
|
||||
if _, err := d.Exec(`INSERT INTO gsc_site_days VALUES (?, ?, ?, ?, ?)`, site, day, site_.clicks, site_.impr, site_.pos*float64(site_.impr)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pages := map[string]row{}
|
||||
for _, r := range rows {
|
||||
p := pages[r.page]
|
||||
p.page = r.page
|
||||
p.pos = (p.pos*float64(p.impr) + r.pos*float64(r.impr)) / float64(p.impr+r.impr)
|
||||
p.clicks += r.clicks
|
||||
p.impr += r.impr
|
||||
pages[r.page] = p
|
||||
if r.query != "" {
|
||||
if _, err := d.Exec(`INSERT INTO gsc_query_days VALUES (?, ?, ?, ?, ?, ?, ?)`, site, day, r.page, r.query, r.clicks, r.impr, r.pos*float64(r.impr)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, p := range pages {
|
||||
if _, err := d.Exec(`INSERT INTO gsc_page_days VALUES (?, ?, ?, ?, ?, ?)`, site, day, p.page, p.clicks, p.impr, p.pos*float64(p.impr)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMorningCheckAndReport(t *testing.T) {
|
||||
d := openDB(t)
|
||||
site := "sc-domain:whey.example"
|
||||
best, review, gone := "https://whey.example/best/", "https://whey.example/review/", "https://whey.example/old/"
|
||||
// The week before: 2026-11-06 to 11-12. This week: 11-13 to 11-19.
|
||||
week(t, d, site, "2026-11-06", row{clicks: 59, impr: 9679, pos: 27}, []row{
|
||||
{best, "whey price comparison", 0, 515, 3.0}, {best, "best whey", 0, 80, 40},
|
||||
{review, "whey review", 8, 400, 10},
|
||||
{gone, "old query", 1, 400, 20},
|
||||
{"https://whey.example/tiny/", "tiny", 1, 20, 30},
|
||||
})
|
||||
week(t, d, site, "2026-11-13", row{clicks: 95, impr: 9763, pos: 25.1}, []row{
|
||||
{best, "whey price comparison", 0, 34, 3.9}, {best, "best whey", 0, 80, 40},
|
||||
{review, "whey review", 15, 420, 6.7},
|
||||
{"https://whey.example/tiny/", "tiny", 2, 22, 31},
|
||||
})
|
||||
d.PutJSON(throughKey(site), "2026-11-19")
|
||||
|
||||
c, err := MorningCheck(d, site, DefaultSettings)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c.From != "2026-11-13" || c.PrevTo != "2026-11-12" || c.Before.Clicks != 59 || c.After.Clicks != 95 {
|
||||
t.Fatalf("check: %+v", c)
|
||||
}
|
||||
moves := map[string]Move{}
|
||||
for _, m := range c.Moves {
|
||||
moves[m.Kind+":"+m.Key] = m
|
||||
}
|
||||
if len(c.Moves) != 5 {
|
||||
t.Errorf("moves: %+v", c.Moves)
|
||||
}
|
||||
// The review page: +7 clicks, and the query behind it.
|
||||
r := moves["page:"+review]
|
||||
if r.ClickDelta() != 7 || !strings.Contains(strings.Join(r.Why, " "), "“whey review”: 8 → 15 clicks") {
|
||||
t.Errorf("review: %+v", r)
|
||||
}
|
||||
// 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") ||
|
||||
!strings.Contains(why, "“whey price comparison”, 0 → 0 clicks, 515 → 34 impressions, position 3.0 → 3.9") {
|
||||
t.Errorf("best: %+v %v", b, why)
|
||||
}
|
||||
// A page with no row this week is "no data", not a drop to zero.
|
||||
if g := moves["page:"+gone]; !g.NoData || !strings.Contains(g.Why[0], "no data") {
|
||||
t.Errorf("gone: %+v", g)
|
||||
}
|
||||
if _, ok := moves["page:https://whey.example/tiny/"]; ok {
|
||||
t.Error("noise reported as a move")
|
||||
}
|
||||
if _, ok := moves["query:whey review"]; !ok {
|
||||
t.Error("the review query's move is missing")
|
||||
}
|
||||
|
||||
// Higher thresholds: quiet.
|
||||
q, _ := MorningCheck(d, 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))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if rep.WeekTo != "2026-11-19" || len(rep.Pages) != 3 || rep.Pages[0].Key != review ||
|
||||
rep.Where != "Clicks grew while impressions were flat: the change comes from rank and click rate, not from more visibility. On 95 clicks, one week is not a trend." {
|
||||
t.Fatalf("report: %+v", rep)
|
||||
}
|
||||
if len(rep.Pages[0].Why) == 0 {
|
||||
t.Error("the report's pages have no causes")
|
||||
}
|
||||
if err := Save(d, rep); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := Save(d, rep); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
list, _ := Reports(d, site, 10)
|
||||
if len(list) != 1 || list[0].After.Clicks != 95 || list[0].Pages[0].Key != review {
|
||||
t.Errorf("stored: %+v", list)
|
||||
}
|
||||
text := rep.Text()
|
||||
for _, want := range []string{"Clicks 59 → 95", "Position 27.0 → 25.1", "3. Waiting for your yes", review} {
|
||||
if !strings.Contains(text, want) {
|
||||
t.Errorf("text lacks %q:\n%s", want, text)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWhere(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
b, a Numbers
|
||||
want string
|
||||
}{
|
||||
{Numbers{Clicks: 1000, Impressions: 10000}, Numbers{Clicks: 1200, Impressions: 13000}, "Impressions rose 30%"},
|
||||
{Numbers{Clicks: 1000, Impressions: 10000}, Numbers{Clicks: 800, Impressions: 7000}, "Impressions fell 30%"},
|
||||
{Numbers{Clicks: 1000, Impressions: 10000}, Numbers{Clicks: 1000, Impressions: 10000}, "Clicks didn't change."},
|
||||
} {
|
||||
if got := where(c.b, c.a); !strings.HasPrefix(got, c.want) {
|
||||
t.Errorf("%v → %v: %q", c.b, c.a, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
package seo
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/db"
|
||||
)
|
||||
|
||||
// Report is the Monday report: one page, the same every week.
|
||||
type Report struct {
|
||||
Site string `json:"site"`
|
||||
WeekFrom string `json:"week_from"`
|
||||
WeekTo string `json:"week_to"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Before Numbers `json:"before"`
|
||||
After Numbers `json:"after"`
|
||||
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"`
|
||||
}
|
||||
|
||||
// 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
|
||||
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.Where = where(c.Before, c.After)
|
||||
var pages []Move
|
||||
for _, m := range c.Moves {
|
||||
if m.Kind == "page" && !m.NoData && (m.ClickDelta() != 0 || m.PosDelta() != 0) {
|
||||
pages = append(pages, m)
|
||||
}
|
||||
}
|
||||
slices.SortStableFunc(pages, 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(x.After.Impressions)
|
||||
wy := math.Abs(y.PosDelta()) * float64(y.After.Impressions)
|
||||
switch {
|
||||
case wx > wy:
|
||||
return -1
|
||||
case wx < wy:
|
||||
return 1
|
||||
}
|
||||
return strings.Compare(x.Key, y.Key)
|
||||
})
|
||||
if len(pages) > 3 {
|
||||
pages = pages[:3]
|
||||
}
|
||||
// The causes, from the full check (which explains only real moves).
|
||||
full, err := MorningCheck(d, site, LoadSettings(d))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for i := range pages {
|
||||
for _, m := range full.Moves {
|
||||
if m.Kind == "page" && m.Key == pages[i].Key {
|
||||
pages[i].Why = m.Why
|
||||
}
|
||||
}
|
||||
}
|
||||
r.Pages = pages
|
||||
ranks, err := WhatRanks(d, site)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if ranks != nil {
|
||||
r.Waiting = ranks.Push
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
|
||||
// where says where a week's change in clicks came from.
|
||||
func where(b, a Numbers) string {
|
||||
dc := a.Clicks - b.Clicks
|
||||
var impr float64
|
||||
if b.Impressions > 0 {
|
||||
impr = 100 * float64(a.Impressions-b.Impressions) / float64(b.Impressions)
|
||||
}
|
||||
var s string
|
||||
switch {
|
||||
case b.Impressions == 0 && a.Impressions == 0:
|
||||
return "No impressions in either week."
|
||||
case dc == 0:
|
||||
s = "Clicks didn't change."
|
||||
case math.Abs(impr) < 5:
|
||||
s = fmt.Sprintf("Clicks %s while impressions were flat: the change comes from rank and click rate, not from more visibility.", upDown(dc))
|
||||
case impr > 0 && dc > 0:
|
||||
s = fmt.Sprintf("Impressions rose %.0f%%: more of the gain comes from Google showing the site more.", impr)
|
||||
case impr < 0 && dc < 0:
|
||||
s = fmt.Sprintf("Impressions fell %.0f%%: Google showed the site less.", -impr)
|
||||
case impr > 0:
|
||||
s = fmt.Sprintf("Impressions rose %.0f%% but clicks fell: the site was shown more, for searches where it gets clicked less.", impr)
|
||||
default:
|
||||
s = fmt.Sprintf("Impressions fell %.0f%% but clicks rose: fewer showings, better clicked.", -impr)
|
||||
}
|
||||
if a.Clicks+b.Clicks < 200 && dc != 0 {
|
||||
s += fmt.Sprintf(" On %s clicks, one week is not a trend.", Thousands(a.Clicks))
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func upDown(n int) string {
|
||||
if n > 0 {
|
||||
return "grew"
|
||||
}
|
||||
return "fell"
|
||||
}
|
||||
|
||||
// Save stores a report, replacing one for the same week.
|
||||
func Save(d *db.DB, r *Report) error {
|
||||
raw, err := json.Marshal(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = d.Exec(`INSERT INTO seo_reports (site, week_to, created_at, data) VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT (site, week_to) DO UPDATE SET created_at = excluded.created_at, data = excluded.data`,
|
||||
r.Site, r.WeekTo, r.CreatedAt.UTC().Format(time.RFC3339), string(raw))
|
||||
return err
|
||||
}
|
||||
|
||||
// Reports lists a site's stored reports, newest first.
|
||||
func Reports(d *db.DB, site string, limit int) ([]Report, error) {
|
||||
rows, err := d.Query(`SELECT data FROM seo_reports WHERE site = ? ORDER BY week_to DESC LIMIT ?`, site, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []Report
|
||||
for rows.Next() {
|
||||
var raw string
|
||||
if err := rows.Scan(&raw); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var r Report
|
||||
if err := json.Unmarshal([]byte(raw), &r); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, r)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// GetReport returns a site's report for the week ending on a day.
|
||||
func GetReport(d *db.DB, site, weekTo string) (*Report, error) {
|
||||
var raw string
|
||||
err := d.QueryRow(`SELECT data FROM seo_reports WHERE site = ? AND week_to = ?`, site, weekTo).Scan(&raw)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var r Report
|
||||
if err := json.Unmarshal([]byte(raw), &r); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &r, nil
|
||||
}
|
||||
|
||||
// Text is the report as plain text, for email.
|
||||
func (r *Report) Text() string {
|
||||
var b strings.Builder
|
||||
fmt.Fprintf(&b, "SEO report for %s, %s to %s (against the week before)\n\n", r.Site, r.WeekFrom, r.WeekTo)
|
||||
b.WriteString("1. The week\n")
|
||||
fmt.Fprintf(&b, " Clicks %s → %s\n", Thousands(r.Before.Clicks), Thousands(r.After.Clicks))
|
||||
fmt.Fprintf(&b, " Impressions %s → %s\n", Thousands(r.Before.Impressions), Thousands(r.After.Impressions))
|
||||
fmt.Fprintf(&b, " Position %.1f → %.1f\n", r.Before.Position, r.After.Position)
|
||||
fmt.Fprintf(&b, " %s\n\n", r.Where)
|
||||
b.WriteString("2. The pages that moved most\n")
|
||||
if len(r.Pages) == 0 {
|
||||
b.WriteString(" None.\n")
|
||||
}
|
||||
for _, m := range r.Pages {
|
||||
fmt.Fprintf(&b, " %s: %s\n", m.Key, change(m.Before, m.After))
|
||||
for _, w := range m.Why {
|
||||
fmt.Fprintf(&b, " %s\n", w)
|
||||
}
|
||||
}
|
||||
b.WriteString("\n3. Waiting for your yes\n")
|
||||
if len(r.Waiting) == 0 {
|
||||
b.WriteString(" Nothing this week.\n")
|
||||
}
|
||||
for i, p := range r.Waiting {
|
||||
fmt.Fprintf(&b, " %d. %s\n %s\n", i+1, p.Page, p.Why)
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
Reference in New Issue
Block a user