diff --git a/PLAN.md b/PLAN.md index abdc1f6..ae3a236 100644 --- a/PLAN.md +++ b/PLAN.md @@ -726,6 +726,7 @@ into `main`. - Settings → Search engines: keys, the redirect URI, Connect, and the property for each website, saved in the profile. - SEO → What ranks, with a sync twice a day. + Committed as 5ea620a. 2. **Morning check and Monday report (jobs 6 and 7)**, computed in code. - **Morning check:** the last 7 final days against the 7 before, by page and by query. It reports only moves past the thresholds (default: @@ -743,6 +744,26 @@ into `main`. 3. A list called "Waiting for your yes", with at most 3 changes. - Kept as history, so reports can be compared. Optionally emailed to the user through the Core's mail server. + - **Built 2026-11-22** (schema 13: `seo_reports`): + - `seo.MorningCheck` compares the last 7 final days with the 7 + before, for pages and for searches. Pages that vanished show as + "no data". New ones count once they reach the impressions + threshold. + - A page's move is explained by the search whose clicks changed most, + and a like-for-like position: the searches it had both weeks, + weighted by this week's impressions. When that's under half the + move, the cause is the mix of searches. The search whose + impressions changed most is named. + - `seo.Weekly` writes the three numbers and a sentence on where the + change came from: rank and click rate, or visibility, plus "one + week is not a trend" under 200 clicks. It adds the 3 pages that + moved most, with causes. "Waiting for your yes" holds job 1's + *Push* pages until part 4 brings exact changes. + - Written on Mondays (or when the last report is over a week old), + stored, and optionally emailed through the outreach mailbox + (`outreach.SendToSelf`). + - The thresholds and the email option are under Settings → Search + engines; the pages are SEO → Morning check and Monday report. 3. **Technical audit, weighted by traffic, plus AI visibility.** - A crawler (within the site's sitemap and links, polite, robots.txt honoured) checks each page's: diff --git a/README.md b/README.md index 3e46765..4307063 100644 --- a/README.md +++ b/README.md @@ -106,6 +106,8 @@ To check the connection, open **Core & Hermes** in Supermarket and ask Hermes th **SEO: what already ranks (SEO → What ranks, and Settings → Search engines).** Connect Google Search Console (an OAuth client from your own Google Cloud project, read-only) and choose each website's property. Supermarket reads 16 months of Search Console data, then syncs twice a day. The page shows the last 90 days of final data: clicks, impressions, click rate and average position; how much of the traffic comes from searches Google doesn't name; your best pages; the searches you're shown for most and hardly clicked; the pages to protect (they carry the clicks) and the pages to push (on page one, shown a lot, rarely clicked), each with the number that justifies it and the search it's mostly shown for. Every number is Google's; nothing is estimated. +**SEO: the morning check and the Monday report.** *Morning check* compares the last 7 days of final Search Console data with the 7 before, by page and by search, and lists only real moves. A move means more than 5 clicks, or more than 3 positions on at least 300 impressions; the thresholds are editable under Settings → Search engines. Otherwise it says "Nothing real moved". For each move it shows the numbers before and after, and what the data shows about the cause: which search's clicks changed, and whether a position change is real or only Google showing the page for a different mix of searches. A search with no row this week is "no data", not a drop to zero. The *Monday report* is one page, the same every week: clicks, impressions and position against the week before, with a sentence on where the change came from; the 3 pages that moved most; and "Waiting for your yes", at most 3 pages to act on. It's written every Monday, kept for comparison, and can be emailed to you through the outreach mailbox. + **The end of the funnel (Settings → Website & sales).** When writing posts on Content, choose *For a buying signal*: the posts speak to that situation, and their links carry the signal's campaign tag. Each signal's page lists its posts and gives your websites' addresses tagged with it, for landing pages, the shopping cart or links you share. With a Plausible Stats API key (Plausible on your Core by default), Supermarket reads yesterday's visitors on tagged links once a day and counts them as Visited for the signal, by channel; visits are counted per signal, never per person. With a restricted, read-only Stripe key, it reads new checkouts and paid invoices every hour: a checkout with nothing to pay (a trial or a free plan) counts as Signed up, and money paid as Paid, with the amount. A customer is tied to a signal by the `utm_campaign` your shopping cart saves in the Checkout Session's metadata, or else by their email (a prospect's, or one at a prospect company's domain). Your Core's Cal.com has no API, so bookings are read from Cal.com's booking emails in the outreach mailbox: give Cal.com's sending address under Settings → Email, and each new booking counts as Booked for the person who booked. **Prospects (Prospects → Review).** Companies and people who may fit your targets wait here for review; for now you add them by hand, and finding them for you comes next. Each keeps where and when it was found. Accepting a company queues an EspoCRM Account, accepting a person queues a Lead at their company, with the source, date and why they fit in the record's description. Before you decide, the page warns about records already in your CRM (as of the last sync). *Set aside* keeps a prospect out of the way; the **suppression list** (Prospects → Suppression list) holds emails and domains that must never be added, and is checked when a prospect is added and again before anything is queued. diff --git a/TEST.md b/TEST.md index e1746e1..0b5d062 100644 --- a/TEST.md +++ b/TEST.md @@ -294,6 +294,24 @@ Throughout, also notice: the search it names is the one it's shown for most. - [ ] With several websites, the tabs switch between them. +### Morning check and Monday report + +- [ ] SEO → Morning check names the two weeks it compares, and its totals + match Search Console's Performance report for those dates. +- [ ] Only moves past the thresholds are listed; with nothing past them it + says "Nothing real moved". Changing the thresholds under Settings → + Search engines changes the list. +- [ ] For a page whose average position jumped, the explanation says whether + it really moved on its searches or Google showed it for a different + mix; check one against Search Console's Queries tab for that page. +- [ ] A search that disappeared says "no data", not 0. +- [ ] SEO → Monday report: *Write it now* writes this week's report: the + three numbers with the sentence under them, the 3 pages that moved + most, and "Waiting for your yes" (at most 3). +- [ ] Earlier reports are listed and open. +- [ ] **(real)** With *Email me the Monday report* on and email set up, the + report arrives on Monday morning. + ## 8. Search - [ ] Searching for an inventory entry, a fetched item, a post, a prospect diff --git a/internal/db/db.go b/internal/db/db.go index 9bc325e..94c161d 100644 --- a/internal/db/db.go +++ b/internal/db/db.go @@ -394,6 +394,16 @@ CREATE TABLE gsc_query_days ( PRIMARY KEY (site, date, page, query) ); CREATE INDEX gsc_query_days_by_query ON gsc_query_days (site, query, date); +`, + // 13: the Monday SEO reports, kept so each week compares with the last. + ` +CREATE TABLE seo_reports ( + site TEXT NOT NULL, + week_to TEXT NOT NULL, -- the week's last day of final data + created_at TEXT NOT NULL, + data TEXT NOT NULL, -- the report, as JSON + PRIMARY KEY (site, week_to) +); `, } diff --git a/internal/outreach/send.go b/internal/outreach/send.go index a25f024..71d4463 100644 --- a/internal/outreach/send.go +++ b/internal/outreach/send.go @@ -138,3 +138,11 @@ func SendTest(ctx context.Context, s Settings, snd Sender, now time.Time) error newMessageID(0, s.FromDomain()), now) return snd.Send(ctx, e) } + +// SendToSelf emails the From address itself (a report, for instance), +// without the outreach signature. +func SendToSelf(ctx context.Context, s Settings, snd Sender, subject, body string, now time.Time) error { + s.Footer = "" + e := Compose(s, s.FromName, s.FromAddress, subject, body, newMessageID(0, s.FromDomain()), now) + return snd.Send(ctx, e) +} diff --git a/internal/seo/check.go b/internal/seo/check.go new file mode 100644 index 0000000..7ed047f --- /dev/null +++ b/internal/seo/check.go @@ -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) +} diff --git a/internal/seo/check_test.go b/internal/seo/check_test.go new file mode 100644 index 0000000..a62ce54 --- /dev/null +++ b/internal/seo/check_test.go @@ -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) + } + } +} diff --git a/internal/seo/report.go b/internal/seo/report.go new file mode 100644 index 0000000..e994994 --- /dev/null +++ b/internal/seo/report.go @@ -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() +} diff --git a/internal/web/seo.go b/internal/web/seo.go index 0395110..e26abf7 100644 --- a/internal/web/seo.go +++ b/internal/web/seo.go @@ -12,6 +12,7 @@ import ( "supermarket/internal/api/gsc" "supermarket/internal/oauth" + "supermarket/internal/outreach" "supermarket/internal/profile" "supermarket/internal/secrets" "supermarket/internal/seo" @@ -116,6 +117,7 @@ func (s *Server) renderSearchSettings(w http.ResponseWriter, r *http.Request, er "Sites": s.seoSites(), "Connected": s.Secrets.Has(secrets.GoogleRefreshToken), "Account": s.connections()["google"].Account, + "SEO": seo.LoadSettings(s.DB), } if c := s.gsc(); c != nil { ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second) @@ -147,6 +149,16 @@ func (s *Server) searchSettingsSave(w http.ResponseWriter, r *http.Request) { gauth.token = "" gauth.mu.Unlock() } + if _, has := r.PostForm["min_clicks"]; has { + f := r.PostFormValue + clicks, _ := strconv.Atoi(f("min_clicks")) + impr, _ := strconv.Atoi(f("min_impressions")) + pos, _ := strconv.ParseFloat(f("min_positions"), 64) + if err := seo.SaveSettings(s.DB, seo.Settings{MinClicks: clicks, MinPositions: pos, MinImpressions: impr, EmailReport: f("email_report") == "on"}); err != nil { + s.renderSearchSettings(w, r, err.Error()) + return + } + } if props, has := r.PostForm["property"]; has { p, err := profile.Load(s.DB) if err != nil { @@ -225,6 +237,7 @@ func (s *Server) RunSEO(ctx context.Context) { } cancel() } + s.weeklyReports(ctx, time.Now()) } select { case <-ctx.Done(): @@ -237,30 +250,8 @@ func (s *Server) RunSEO(ctx context.Context) { // --- The SEO page --- func (s *Server) seoPage(w http.ResponseWriter, r *http.Request) { - sites := s.seoSites() - var mapped []seoSite - for _, st := range sites { - if st.Property != "" { - mapped = append(mapped, st) - } - } - var cur *seoSite - if i, err := strconv.Atoi(r.URL.Query().Get("site")); err == nil { - for j := range mapped { - if mapped[j].Index == i { - cur = &mapped[j] - } - } - } - if cur == nil && len(mapped) > 0 { - cur = &mapped[0] - } - data := map[string]any{ - "Connected": s.Secrets.Has(secrets.GoogleRefreshToken), - "Sites": mapped, - "Current": cur, - "Days": seo.RanksDays, - } + data, cur := s.seoBase(r) + data["Path"], data["Days"] = "/seo", seo.RanksDays if cur != nil { ranks, err := seo.WhatRanks(s.DB, cur.Property) if err != nil { @@ -283,3 +274,147 @@ func pagePath(u string) string { } return p.Path } + +// seoCurrent is the site the request asks for (?site=), or the first. +func (s *Server) seoCurrent(r *http.Request) ([]seoSite, *seoSite) { + var mapped []seoSite + for _, st := range s.seoSites() { + if st.Property != "" { + mapped = append(mapped, st) + } + } + if i, err := strconv.Atoi(r.URL.Query().Get("site")); err == nil { + for j := range mapped { + if mapped[j].Index == i { + return mapped, &mapped[j] + } + } + } + if len(mapped) > 0 { + return mapped, &mapped[0] + } + return mapped, nil +} + +func (s *Server) seoBase(r *http.Request) (map[string]any, *seoSite) { + sites, cur := s.seoCurrent(r) + return map[string]any{ + "Connected": s.Secrets.Has(secrets.GoogleRefreshToken), + "Sites": sites, + "Current": cur, + }, cur +} + +// seoCheckPage is the morning check. +func (s *Server) seoCheckPage(w http.ResponseWriter, r *http.Request) { + data, cur := s.seoBase(r) + data["Path"] = "/seo/check" + if cur != nil { + c, err := seo.MorningCheck(s.DB, cur.Property, seo.LoadSettings(s.DB)) + if err != nil { + s.serverError(w, err) + return + } + data["Check"] = c + if c != nil && len(c.Moves) > 25 { + data["More"] = len(c.Moves) - 25 + c.Moves = c.Moves[:25] + } + } + s.render(w, r, "seo-check", page{Title: "Morning check", Nav: "seo/check", Data: data}) +} + +// seoReportPage shows a stored Monday report (the latest, or ?week=). +func (s *Server) seoReportPage(w http.ResponseWriter, r *http.Request) { + data, cur := s.seoBase(r) + data["Path"] = "/seo/report" + if cur != nil { + list, err := seo.Reports(s.DB, cur.Property, 12) + if err != nil { + s.serverError(w, err) + return + } + data["Reports"] = list + var rep *seo.Report + if wk := r.URL.Query().Get("week"); wk != "" { + rep, _ = seo.GetReport(s.DB, cur.Property, wk) + } else if len(list) > 0 { + rep = &list[0] + } + data["Report"] = rep + if rep != nil { + for i := range list { + if list[i].WeekTo < rep.WeekTo { + data["Previous"] = &list[i] + break + } + } + } + } + s.render(w, r, "seo-report", page{Title: "Monday report", Nav: "seo/report", Data: data}) +} + +// seoReportWrite writes this week's report now. +func (s *Server) seoReportWrite(w http.ResponseWriter, r *http.Request) { + _, cur := s.seoCurrent(r) + if cur == nil { + http.NotFound(w, r) + return + } + rep, err := s.writeReport(r.Context(), *cur, false) + if err != nil { + s.serverError(w, err) + return + } + if rep == nil { + redirect(w, r, "/seo/report?site="+strconv.Itoa(cur.Index), "no-data") + return + } + redirect(w, r, "/seo/report?site="+strconv.Itoa(cur.Index)+"&week="+rep.WeekTo, "report-written") +} + +// writeReport builds and stores a site's report, and emails it if the +// settings say so (and email is set up). +func (s *Server) writeReport(ctx context.Context, site seoSite, email bool) (*seo.Report, error) { + rep, err := seo.Weekly(s.DB, site.Property, time.Now()) + if err != nil || rep == nil { + return rep, err + } + if err := seo.Save(s.DB, rep); err != nil { + return nil, err + } + if email && seo.LoadSettings(s.DB).EmailReport { + if set, mb, err := s.mailbox(); err == nil { + ectx, cancel := context.WithTimeout(ctx, 2*time.Minute) + err = outreach.SendToSelf(ectx, set, mb, "SEO report: "+site.URL+", week to "+rep.WeekTo, rep.Text(), time.Now()) + cancel() + if err != nil { + s.Log.Warn("seo: emailing the report", "err", err) + } + } + } + return rep, nil +} + +// weeklyReports writes each site's Monday report once its week's data is +// in: on Mondays, or when the last report is more than a week old. +func (s *Server) weeklyReports(ctx context.Context, now time.Time) { + for _, site := range s.seoSites() { + if site.Property == "" || seo.Through(s.DB, site.Property) == "" { + continue + } + list, err := seo.Reports(s.DB, site.Property, 1) + if err != nil { + s.Log.Warn("seo: reports", "err", err) + continue + } + stale := len(list) == 0 || now.Sub(list[0].CreatedAt) > 7*24*time.Hour + monday := now.Weekday() == time.Monday && now.Hour() >= 6 && (len(list) == 0 || now.Sub(list[0].CreatedAt) > 24*time.Hour) + if !stale && !monday { + continue + } + if _, err := s.writeReport(ctx, site, true); err != nil { + s.Log.Warn("seo: writing the report", "site", site.Property, "err", err) + } + } +} diff --git a/internal/web/seo_test.go b/internal/web/seo_test.go index 52cb993..4d13c1b 100644 --- a/internal/web/seo_test.go +++ b/internal/web/seo_test.go @@ -100,4 +100,31 @@ func TestSearchConsole(t *testing.T) { t.Errorf("SEO page lacks %q", want) } } + + // The morning check: last week has data, the week before none, so the + // pages are new. + body = do(h, http.MethodGet, "/seo/check", nil, nil).Body.String() + for _, want := range []string{"2026-11-04 to 2026-11-10", "/pricing/", "new"} { + if !strings.Contains(body, want) { + t.Errorf("check lacks %q", want) + } + } + if body := do(h, http.MethodGet, "/seo/report", nil, nil).Body.String(); !strings.Contains(body, "No report yet") { + t.Error("a report before one was written") + } + rec = postForm(h, "/seo/report?site=0", nil) + if rec.Code != http.StatusSeeOther || !strings.Contains(rec.Header().Get("Location"), "week=2026-11-10") { + t.Fatalf("write report: %d %s %s", rec.Code, rec.Header().Get("Location"), rec.Body) + } + body = do(h, http.MethodGet, "/seo/report", nil, nil).Body.String() + for _, want := range []string{"1. The week", "Waiting for your yes", "/pricing/", "4,200"} { + if !strings.Contains(body, want) { + t.Errorf("report lacks %q", want) + } + } + // Thresholds. + postForm(h, "/settings/search", url.Values{"min_clicks": {"10"}, "min_positions": {"2.5"}, "min_impressions": {"500"}, "email_report": {"on"}}) + if body := do(h, http.MethodGet, "/settings/search", nil, nil).Body.String(); !strings.Contains(body, `name="min_positions" inputmode="decimal" value="2.5"`) || !strings.Contains(body, `name="email_report" checked`) { + t.Error("thresholds weren't saved") + } } diff --git a/internal/web/server.go b/internal/web/server.go index d2ba10f..68e5717 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -160,6 +160,9 @@ func (s *Server) Handler() (http.Handler, error) { mux.HandleFunc("POST /settings/email/test", s.emailTest) mux.HandleFunc("POST /settings/email/send-test", s.emailSendTest) mux.HandleFunc("GET /seo", s.seoPage) + mux.HandleFunc("GET /seo/check", s.seoCheckPage) + mux.HandleFunc("GET /seo/report", s.seoReportPage) + mux.HandleFunc("POST /seo/report", s.seoReportWrite) mux.HandleFunc("GET /settings/search", s.searchSettingsPage) mux.HandleFunc("POST /settings/search", s.searchSettingsSave) mux.HandleFunc("POST /settings/search/sync", s.seoSync) @@ -405,6 +408,8 @@ var flashes = map[string]string{ "li-connected": "LinkedIn is connected.", "google-connected": "Search Console is connected. Choose each website's property below, then sync.", "synced": "Synced from Search Console.", + "report-written": "This week's report is written.", + "no-data": "There isn't two weeks of Search Console data yet.", "reddit-connected": "Reddit is connected.", "crm-test": "Test Lead queued. Hermes creates it on its next run; or run it now (below).", "crm-sync": "Sync requested: Hermes copies CRM records on its next run.", diff --git a/internal/web/server_test.go b/internal/web/server_test.go index c67036b..1017e43 100644 --- a/internal/web/server_test.go +++ b/internal/web/server_test.go @@ -100,7 +100,7 @@ func TestEveryPageRenders(t *testing.T) { "/settings/ai", "/settings/accounts", "/settings/core", "/static/app.css", "/favicon.ico", "/static/favicon.png", "/static/logo.png", "/static/apple-touch-icon.png", "/search", "/crm", "/search?q=rival", "/search?q=nothing+here", "/static/htmx.min.js", "/healthz", "/content", "/content/1", "/content/1?dismissed=1", "/posts", "/posts?msg=drafted", "/content/scheduled", "/content/published", - "/prospects", "/prospects?status=accepted", "/prospects?status=rejected", "/prospects/new", "/prospects/suppressed", "/outreach", "/outreach?tab=queued", "/outreach?tab=sent", "/outreach?tab=replied", "/outreach?tab=failed", "/settings/email", "/settings/tracking", "/settings/search", "/seo", + "/prospects", "/prospects?status=accepted", "/prospects?status=rejected", "/prospects/new", "/prospects/suppressed", "/outreach", "/outreach?tab=queued", "/outreach?tab=sent", "/outreach?tab=replied", "/outreach?tab=failed", "/settings/email", "/settings/tracking", "/settings/search", "/seo", "/seo/check", "/seo/report", "/signals", "/signals?period=30d&channel=email", "/signals/new", "/settings/sources"} { rec := do(h, http.MethodGet, path, nil, nil) if rec.Code != http.StatusOK { diff --git a/internal/web/templates/layout.html b/internal/web/templates/layout.html index ba779fb..0d432ae 100644 --- a/internal/web/templates/layout.html +++ b/internal/web/templates/layout.html @@ -40,6 +40,8 @@ {{end}} {{if eq .ID "seo"}} {{end}} @@ -152,3 +154,13 @@ {{- else if eq . "core"}} {{- else if eq . "menu"}} {{- end}}{{end}} + +{{define "seo-sites"}} +{{if not .Connected}} +

Connect Google Search Console under Settings → Search engines first.

+{{else if not .Sites}} +

Choose the Search Console property for your website under Settings → Search engines.

+{{else if gt (len .Sites) 1}}{{$d := .}} + +{{end}} +{{end}} diff --git a/internal/web/templates/search-engines.html b/internal/web/templates/search-engines.html index 24d2810..88e74a6 100644 --- a/internal/web/templates/search-engines.html +++ b/internal/web/templates/search-engines.html @@ -33,6 +33,19 @@ {{end}} +{{if .Connected}}{{$s := .SEO}} +
+

The morning check and the Monday report

+

A page or search counts as a real move when its clicks change by more than this many, or its position by more than this many places on at least this many impressions. Raise them if the check lists too much; on a small site an average position jumps as soon as one search appears or disappears.

+
+ + + +
+ +
+{{end}} +
diff --git a/internal/web/templates/seo-check.html b/internal/web/templates/seo-check.html new file mode 100644 index 0000000..82269db --- /dev/null +++ b/internal/web/templates/seo-check.html @@ -0,0 +1,39 @@ +{{define "content"}}{{with .Data}}{{$d := .}} +
+

Morning check

+ {{if .Current}}
+
+
{{end}} +
+

The last 7 days of final Search Console data against the 7 before, by page and by search. Only real moves are listed: the thresholds are under Settings → Search engines. Causes are what the data shows, which is correlation, not proof.

+ +{{template "seo-sites" .}} +{{if .Current}} +{{with .Check}} +
+

{{.From}} to {{.To}}, against {{.PrevFrom}} to {{.PrevTo}} · {{.Pages}} pages and {{.Queries}} searches compared

+

Clicks {{num .Before.Clicks}} → {{num .After.Clicks}} · impressions {{num .Before.Impressions}} → {{num .After.Impressions}} · position {{dec1 .Before.Position}} → {{dec1 .After.Position}}

+ {{if .Quiet}}

Nothing real moved.

{{end}} +
+{{if not .Quiet}} + + + + {{range .Moves}} + + + {{if .NoData}} + {{else if .New}} + {{else}}{{end}} + + + {{end}} + +
Page or searchClicksImpressionsPositionWhat the data shows
{{if eq .Kind "page"}}{{pagePath .Key}}{{else}}search {{.Key}}{{end}}{{num .Before.Clicks}} → no data{{num .Before.Impressions}} → no data{{dec1 .Before.Position}} → no datanew {{num .After.Clicks}}{{num .After.Impressions}}{{dec1 .After.Position}}{{num .Before.Clicks}} → {{num .After.Clicks}}{{num .Before.Impressions}} → {{num .After.Impressions}}{{dec1 .Before.Position}} → {{dec1 .After.Position}}{{range .Why}}{{.}} {{end}}
+{{with $d.More}}

And {{.}} more: raise the thresholds if this is too much to read with your coffee.

{{end}} +{{end}} +{{else}} +

There isn't two weeks of Search Console data yet. Sync, and check again.

+{{end}} +{{end}} +{{end}}{{end}} diff --git a/internal/web/templates/seo-report.html b/internal/web/templates/seo-report.html new file mode 100644 index 0000000..524363e --- /dev/null +++ b/internal/web/templates/seo-report.html @@ -0,0 +1,51 @@ +{{define "content"}}{{with .Data}}{{$d := .}} +
+

Monday report

+ {{if .Current}}
+
+
{{end}} +
+

One page, the same every week, so this Monday compares with the last in seconds: three numbers, the three pages that moved most, and the changes waiting for your yes. It's written every Monday{{if .Current}}, and can be emailed to you (Settings → Search engines){{end}}.

+ +{{template "seo-sites" .}} +{{if .Current}} +{{with .Report}} +
+

{{.WeekFrom}} to {{.WeekTo}}, against the week before · written {{ago .CreatedAt}}

+

1. The week

+
+
Clicks{{num .After.Clicks}}was {{num .Before.Clicks}}
+
Impressions{{num .After.Impressions}}was {{num .Before.Impressions}}
+
Position{{dec1 .After.Position}}was {{dec1 .Before.Position}}
+
+

{{.Where}}

+
+ +
+

2. The pages that moved most

+ {{range .Pages}} +

{{pagePath .Key}}: clicks {{num .Before.Clicks}} → {{num .After.Clicks}}, position {{dec1 .Before.Position}} → {{dec1 .After.Position}} + {{with .Why}}
{{range .}}{{.}} {{end}}{{end}}

+ {{else}}

No page moved.

{{end}} +
+ +
+

3. Waiting for your yes

+ {{range .Waiting}} +

{{pagePath .Page}}
{{.Why}}

+ {{else}}

Nothing this week.

{{end}} +

Each one is a page that ranks on page one and isn't clicked. The exact change to make (a new title or description, with its length) and the pull request that applies it come with the next part.

+
+{{else}} +

No report yet. It's written on Monday once there are two weeks of data, or now with Write it now.

+{{end}} + +{{if gt (len .Reports) 1}} +

Earlier reports

+ + + {{range .Reports}}{{end}} +
Week toClicksImpressionsPosition
{{.WeekTo}}{{num .After.Clicks}}{{num .After.Impressions}}{{dec1 .After.Position}}
+{{end}} +{{end}} +{{end}}{{end}} diff --git a/internal/web/templates/seo.html b/internal/web/templates/seo.html index 2bf9b07..cb612fa 100644 --- a/internal/web/templates/seo.html +++ b/internal/web/templates/seo.html @@ -7,13 +7,8 @@

The cheapest traffic is on pages that already rank. From Search Console, the last {{.Days}} days: the pages that carry your clicks, which to protect, and which to push because Google already shows them and nobody clicks.

-{{if not .Connected}} -

Connect Google Search Console under Settings → Search engines first.

-{{else if not .Sites}} -

Choose the Search Console property for your website under Settings → Search engines.

-{{else}} -{{if gt (len .Sites) 1}}{{end}} - +{{template "seo-sites" .}} +{{if .Current}} {{with .Ranks}}

{{.Site}} · {{.From}} to {{.To}} (Search Console's final data is 2 to 3 days behind).