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>
This commit is contained in:
@@ -4,6 +4,7 @@ import (
|
||||
"fmt"
|
||||
"math"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/db"
|
||||
@@ -16,6 +17,7 @@ type Settings struct {
|
||||
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
|
||||
@@ -73,6 +75,10 @@ type Check struct {
|
||||
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.
|
||||
@@ -236,6 +242,24 @@ func MorningCheck(d *db.DB, sc Scope, set Settings) (*Check, error) {
|
||||
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
|
||||
@@ -362,3 +386,34 @@ func change(b, a Numbers) string {
|
||||
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()
|
||||
}
|
||||
|
||||
@@ -201,3 +201,45 @@ func TestPlaces(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDailyGainsAndOutside(t *testing.T) {
|
||||
d := openDB(t)
|
||||
const site = "sc-domain:whey.example"
|
||||
week(t, d, site, "2026-11-06", row{}, []row{
|
||||
{"https://whey.example/best/", "best whey", 10, 200, 6},
|
||||
{"https://whey.example/best/", "whey deals", 4, 100, 9},
|
||||
{"https://gitea.whey.example/x.sql", "filetype:sql intext:password", 0, 5, 3},
|
||||
})
|
||||
week(t, d, site, "2026-11-13", row{}, []row{
|
||||
{"https://whey.example/best/", "best whey", 15, 300, 5},
|
||||
{"https://whey.example/best/", "whey price", 2, 40, 12},
|
||||
{"https://gitea.whey.example/x.sql", "filetype:sql intext:password", 3, 9, 2},
|
||||
{"https://shop.whey.example/", "whey shop", 1, 9, 2},
|
||||
})
|
||||
d.PutJSON(throughKey(site), "2026-11-19")
|
||||
c, err := MorningCheck(d, NewScope(site, "https://whey.example/"), DefaultSettings)
|
||||
if err != nil || c == nil {
|
||||
t.Fatal(c, err)
|
||||
}
|
||||
if len(c.Days) != 7 || c.Days[0].Date != "2026-11-13" || c.Days[0].Clicks != 17 || c.Days[6].Clicks != 0 || c.PrevDays[0].Clicks != 14 {
|
||||
t.Errorf("days: %+v %+v", c.Days, c.PrevDays)
|
||||
}
|
||||
if len(c.Gains) != 2 || c.Gains[0].Query != "best whey" || c.Gains[1].Query != "whey price" || !c.Gains[1].New {
|
||||
t.Errorf("gains: %+v", c.Gains)
|
||||
}
|
||||
if len(c.Losses) != 1 || c.Losses[0].Query != "whey deals" || !c.Losses[0].NoData {
|
||||
t.Errorf("losses: %+v", c.Losses)
|
||||
}
|
||||
if len(c.Outside) != 2 || c.Outside[0].Host != "gitea.whey.example" || c.Outside[0].Clicks != 3 || c.Outside[0].Query != "filetype:sql intext:password" {
|
||||
t.Errorf("outside: %+v", c.Outside)
|
||||
}
|
||||
text := c.Text("https://whey.example/")
|
||||
for _, want := range []string{"Clicks 14 → 17 (+21.4%)", "Not counted: 3 clicks went to gitea.whey.example, most for “filetype:sql intext:password”.", "Searches that lost most clicks", "whey deals"} {
|
||||
if !strings.Contains(text, want) {
|
||||
t.Errorf("text lacks %q:\n%s", want, text)
|
||||
}
|
||||
}
|
||||
if Percent(37, 30) != "−18.9%" || Percent(5171, 7876) != "+52.3%" || Percent(0, 5) != "" {
|
||||
t.Error("Percent")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,240 @@
|
||||
package seo
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/db"
|
||||
)
|
||||
|
||||
// Day is one day's clicks and impressions.
|
||||
type Day struct {
|
||||
Date string `json:"date"`
|
||||
Clicks int `json:"clicks"`
|
||||
Impressions int `json:"impressions"`
|
||||
}
|
||||
|
||||
// days are the scope's numbers for each day from from to to, with 0 for a
|
||||
// day Search Console has no row for.
|
||||
func days(d *db.DB, sc Scope, from, to string) ([]Day, error) {
|
||||
var rows *sql.Rows
|
||||
var err error
|
||||
if len(sc.Hosts) == 0 {
|
||||
rows, err = d.Query(`SELECT date, sum(clicks), sum(impressions) FROM gsc_site_days
|
||||
WHERE site = ? AND date BETWEEN ? AND ? GROUP BY date`, sc.Property, from, to)
|
||||
} else {
|
||||
cond, args := sc.where()
|
||||
rows, err = d.Query(`SELECT date, sum(clicks), sum(impressions) FROM gsc_page_days
|
||||
WHERE `+cond+` AND date BETWEEN ? AND ? GROUP BY date`, append(args, from, to)...)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
got := map[string]Day{}
|
||||
for rows.Next() {
|
||||
var day Day
|
||||
if err := rows.Scan(&day.Date, &day.Clicks, &day.Impressions); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
got[day.Date] = day
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
start, err1 := time.Parse(dayFormat, from)
|
||||
end, err2 := time.Parse(dayFormat, to)
|
||||
if err1 != nil || err2 != nil {
|
||||
return nil, fmt.Errorf("bad period %s to %s", from, to)
|
||||
}
|
||||
var out []Day
|
||||
for t := start; !t.After(end); t = t.AddDate(0, 0, 1) {
|
||||
k := t.Format(dayFormat)
|
||||
day := got[k]
|
||||
day.Date = k
|
||||
out = append(out, day)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// QueryChange is a search's numbers this week and the week before.
|
||||
type QueryChange struct {
|
||||
Query string `json:"query"`
|
||||
Before Numbers `json:"before"`
|
||||
After Numbers `json:"after"`
|
||||
NoData bool `json:"no_data,omitempty"` // no row this week
|
||||
New bool `json:"new,omitempty"` // no row the week before
|
||||
}
|
||||
|
||||
// ClickDelta is the change in clicks.
|
||||
func (q QueryChange) ClickDelta() int { return q.After.Clicks - q.Before.Clicks }
|
||||
|
||||
// PosDelta is the change in average position (negative is up), or 0 when
|
||||
// either week has no position.
|
||||
func (q QueryChange) PosDelta() float64 {
|
||||
if q.Before.Impressions == 0 || q.After.Impressions == 0 {
|
||||
return 0
|
||||
}
|
||||
return q.After.Position - q.Before.Position
|
||||
}
|
||||
|
||||
// TopChanges is how many searches the gaining and losing lists hold.
|
||||
const TopChanges = 5
|
||||
|
||||
// topQueries are the searches whose clicks rose most, and fell most, from
|
||||
// one week to the next: every change counts here, not only real moves.
|
||||
func topQueries(before, after map[string]Numbers, n int) (gains, losses []QueryChange) {
|
||||
for q := range union(after, before) {
|
||||
a, hasA := after[q]
|
||||
b, hasB := before[q]
|
||||
c := QueryChange{Query: q, Before: b, After: a, NoData: !hasA, New: !hasB}
|
||||
switch {
|
||||
case c.ClickDelta() > 0:
|
||||
gains = append(gains, c)
|
||||
case c.ClickDelta() < 0:
|
||||
losses = append(losses, c)
|
||||
}
|
||||
}
|
||||
order := func(x, y QueryChange) int {
|
||||
if dx, dy := abs(x.ClickDelta()), abs(y.ClickDelta()); dx != dy {
|
||||
return dy - dx
|
||||
}
|
||||
if ix, iy := max(x.Before.Impressions, x.After.Impressions), max(y.Before.Impressions, y.After.Impressions); ix != iy {
|
||||
return iy - ix
|
||||
}
|
||||
return strings.Compare(x.Query, y.Query)
|
||||
}
|
||||
slices.SortFunc(gains, order)
|
||||
slices.SortFunc(losses, order)
|
||||
return gains[:min(n, len(gains))], losses[:min(n, len(losses))]
|
||||
}
|
||||
|
||||
// Outside is the clicks a domain property sent to another of its hosts in
|
||||
// a week: a shop, a forum, a Gitea… with the search that brought most.
|
||||
type Outside struct {
|
||||
Host string `json:"host"`
|
||||
Clicks int `json:"clicks"`
|
||||
Impressions int `json:"impressions"`
|
||||
Query string `json:"query,omitempty"`
|
||||
}
|
||||
|
||||
// MaxOutside is how many other hosts are named.
|
||||
const MaxOutside = 3
|
||||
|
||||
// outside sums a week's clicks on the property's other hosts, most first.
|
||||
// It's empty unless the scope narrows a domain property.
|
||||
func outside(d *db.DB, sc Scope, from, to string) ([]Outside, error) {
|
||||
if len(sc.Hosts) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
cond, args := sc.where()
|
||||
_, inside, _ := strings.Cut(cond, " AND ")
|
||||
notIn := "site = ? AND NOT " + inside
|
||||
rows, err := d.Query(`SELECT page, sum(clicks), sum(impressions) FROM gsc_page_days
|
||||
WHERE `+notIn+` AND date BETWEEN ? AND ? GROUP BY page`, append(args, from, to)...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
byHost := map[string]*Outside{}
|
||||
for rows.Next() {
|
||||
var page string
|
||||
var clicks, impr int
|
||||
if err := rows.Scan(&page, &clicks, &impr); err != nil {
|
||||
rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
h := hostOf(page)
|
||||
if byHost[h] == nil {
|
||||
byHost[h] = &Outside{Host: h}
|
||||
}
|
||||
byHost[h].Clicks += clicks
|
||||
byHost[h].Impressions += impr
|
||||
}
|
||||
rows.Close()
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out []Outside
|
||||
for _, o := range byHost {
|
||||
if o.Clicks > 0 {
|
||||
out = append(out, *o)
|
||||
}
|
||||
}
|
||||
slices.SortFunc(out, func(a, b Outside) int {
|
||||
if a.Clicks != b.Clicks {
|
||||
return b.Clicks - a.Clicks
|
||||
}
|
||||
return strings.Compare(a.Host, b.Host)
|
||||
})
|
||||
out = out[:min(MaxOutside, len(out))]
|
||||
// The search that brought each host most clicks.
|
||||
qrows, err := d.Query(`SELECT page, query, sum(clicks) FROM gsc_query_days
|
||||
WHERE `+notIn+` AND date BETWEEN ? AND ? GROUP BY page, query HAVING sum(clicks) > 0`, append(args, from, to)...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer qrows.Close()
|
||||
best := map[string]int{}
|
||||
for qrows.Next() {
|
||||
var page, q string
|
||||
var clicks int
|
||||
if err := qrows.Scan(&page, &q, &clicks); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
h := hostOf(page)
|
||||
for i := range out {
|
||||
if out[i].Host == h && (clicks > best[h] || (clicks == best[h] && q < out[i].Query)) {
|
||||
best[h], out[i].Query = clicks, q
|
||||
}
|
||||
}
|
||||
}
|
||||
return out, qrows.Err()
|
||||
}
|
||||
|
||||
func hostOf(page string) string {
|
||||
if u, err := url.Parse(page); err == nil && u.Hostname() != "" {
|
||||
return strings.ToLower(u.Hostname())
|
||||
}
|
||||
return page
|
||||
}
|
||||
|
||||
// Percent is a change as a percentage of where it started ("+52.3%",
|
||||
// "−18.9%"), or "" when there's nothing to compare with.
|
||||
func Percent(before, after int) string {
|
||||
if before == 0 {
|
||||
return ""
|
||||
}
|
||||
p := 100 * float64(after-before) / float64(before)
|
||||
switch {
|
||||
case p > 0:
|
||||
return fmt.Sprintf("+%.1f%%", p)
|
||||
case p < 0:
|
||||
return fmt.Sprintf("−%.1f%%", -p)
|
||||
}
|
||||
return "0%"
|
||||
}
|
||||
|
||||
// Summary is a search's change in words, as the email shows it.
|
||||
func (q QueryChange) Summary() string {
|
||||
clicks := fmt.Sprintf("clicks %d → %d", q.Before.Clicks, q.After.Clicks)
|
||||
switch {
|
||||
case q.NoData:
|
||||
return clicks[:strings.Index(clicks, "→")+len("→")] + " no data (no row this week)"
|
||||
case q.New:
|
||||
return fmt.Sprintf("clicks %d, new this week, position %.1f", q.After.Clicks, q.After.Position)
|
||||
}
|
||||
return fmt.Sprintf("%s, position %.1f → %.1f", clicks, q.Before.Position, q.After.Position)
|
||||
}
|
||||
|
||||
// Sentence says where the clicks went, in one line.
|
||||
func (o Outside) Sentence() string {
|
||||
s := fmt.Sprintf("Not counted: %d %s went to %s", o.Clicks, plural(o.Clicks, "click", "clicks"), o.Host)
|
||||
if o.Query != "" {
|
||||
s += fmt.Sprintf(", most for “%s”", o.Query)
|
||||
}
|
||||
return s + "."
|
||||
}
|
||||
+49
-12
@@ -15,15 +15,18 @@ import (
|
||||
|
||||
// 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"`
|
||||
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"`
|
||||
Gains []QueryChange `json:"gains,omitempty"` // searches whose clicks rose most
|
||||
Losses []QueryChange `json:"losses,omitempty"` // and fell most
|
||||
Outside []Outside `json:"outside,omitempty"` // clicks on the property's other hosts
|
||||
// Candidates are the pages worth a proposal, when none is waiting.
|
||||
Candidates []Pick `json:"candidates,omitempty"`
|
||||
}
|
||||
@@ -37,6 +40,7 @@ func Weekly(d *db.DB, sc Scope, now time.Time) (*Report, error) {
|
||||
}
|
||||
r := &Report{Site: sc.Property, WeekFrom: c.From, WeekTo: c.To, CreatedAt: now, Before: c.Before, After: c.After}
|
||||
r.Where = where(c.Before, c.After)
|
||||
r.Gains, r.Losses, r.Outside = c.Gains, c.Losses, c.Outside
|
||||
var pages []Move
|
||||
for _, m := range c.Moves {
|
||||
if m.Kind == "page" && !m.NoData && (m.ClickDelta() != 0 || m.PosDelta() != 0) {
|
||||
@@ -201,10 +205,13 @@ 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, " Clicks %s → %s%s\n", Thousands(r.Before.Clicks), Thousands(r.After.Clicks), inParens(Percent(r.Before.Clicks, r.After.Clicks)))
|
||||
fmt.Fprintf(&b, " Impressions %s → %s%s\n", Thousands(r.Before.Impressions), Thousands(r.After.Impressions), inParens(Percent(r.Before.Impressions, r.After.Impressions)))
|
||||
fmt.Fprintf(&b, " Position %.1f → %.1f\n", r.Before.Position, r.After.Position)
|
||||
fmt.Fprintf(&b, " %s\n\n", r.Where)
|
||||
fmt.Fprintf(&b, " %s\n", r.Where)
|
||||
writeOutside(&b, r.Outside)
|
||||
b.WriteString("\n")
|
||||
writeChanges(&b, r.Gains, r.Losses)
|
||||
b.WriteString("2. The pages that moved most\n")
|
||||
if len(r.Pages) == 0 {
|
||||
b.WriteString(" None.\n")
|
||||
@@ -230,3 +237,33 @@ func (r *Report) Text() string {
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func inParens(s string) string {
|
||||
if s == "" {
|
||||
return ""
|
||||
}
|
||||
return " (" + s + ")"
|
||||
}
|
||||
|
||||
// writeChanges writes the searches that gained and lost most, for email.
|
||||
func writeChanges(b *strings.Builder, gains, losses []QueryChange) {
|
||||
for _, list := range []struct {
|
||||
title string
|
||||
qs []QueryChange
|
||||
}{{"Searches that gained most clicks", gains}, {"Searches that lost most clicks", losses}} {
|
||||
if len(list.qs) == 0 {
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(b, "%s\n", list.title)
|
||||
for _, q := range list.qs {
|
||||
fmt.Fprintf(b, " %-40s %s\n", q.Query, q.Summary())
|
||||
}
|
||||
b.WriteString("\n")
|
||||
}
|
||||
}
|
||||
|
||||
func writeOutside(b *strings.Builder, out []Outside) {
|
||||
for _, o := range out {
|
||||
fmt.Fprintf(b, " %s\n", o.Sentence())
|
||||
}
|
||||
}
|
||||
|
||||
+52
-1
@@ -3,6 +3,7 @@ package web
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sort"
|
||||
@@ -177,7 +178,8 @@ func (s *Server) searchSettingsSave(w http.ResponseWriter, r *http.Request) {
|
||||
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 {
|
||||
if err := seo.SaveSettings(s.DB, seo.Settings{MinClicks: clicks, MinPositions: pos, MinImpressions: impr,
|
||||
EmailReport: f("email_report") == "on", EmailCheck: f("email_check") == "on"}); err != nil {
|
||||
s.renderSearchSettings(w, r, err.Error())
|
||||
return
|
||||
}
|
||||
@@ -274,6 +276,7 @@ func (s *Server) RunSEO(ctx context.Context) {
|
||||
cancel()
|
||||
}
|
||||
s.weeklyReports(ctx, time.Now())
|
||||
s.dailyChecks(ctx)
|
||||
}
|
||||
s.refreshChanges(ctx)
|
||||
s.refreshBriefs(ctx)
|
||||
@@ -362,6 +365,9 @@ func (s *Server) seoCheckPage(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
data["Check"] = c
|
||||
if c != nil {
|
||||
data["Chart"] = newClickChart(c.Days, c.PrevDays)
|
||||
}
|
||||
if c != nil && len(c.Moves) > 25 {
|
||||
data["More"] = len(c.Moves) - 25
|
||||
c.Moves = c.Moves[:25]
|
||||
@@ -465,6 +471,51 @@ func (s *Server) weeklyReports(ctx context.Context, now time.Time) {
|
||||
}
|
||||
}
|
||||
|
||||
func checkEmailedKey(property string) string { return "seo:check-emailed:" + property }
|
||||
|
||||
// dailyChecks emails each site's morning check, once for each new day of
|
||||
// final data, when something really moved and the settings ask for it.
|
||||
func (s *Server) dailyChecks(ctx context.Context) {
|
||||
set := seo.LoadSettings(s.DB)
|
||||
if !set.EmailCheck {
|
||||
return
|
||||
}
|
||||
for _, site := range s.seoSites() {
|
||||
if site.Property == "" {
|
||||
continue
|
||||
}
|
||||
c, err := seo.MorningCheck(s.DB, site.scope(), set)
|
||||
if err != nil {
|
||||
s.Log.Warn("seo: the morning check", "site", site.Property, "err", err)
|
||||
continue
|
||||
}
|
||||
if c == nil {
|
||||
continue
|
||||
}
|
||||
var sent string
|
||||
_, _ = s.DB.GetJSON(checkEmailedKey(site.Property), &sent)
|
||||
if sent == c.To {
|
||||
continue
|
||||
}
|
||||
if !c.Quiet() {
|
||||
mailSet, mb, err := s.mailbox()
|
||||
if err != nil {
|
||||
return // email isn't set up: nothing to send with
|
||||
}
|
||||
ectx, cancel := context.WithTimeout(ctx, 2*time.Minute)
|
||||
err = outreach.SendToSelf(ectx, mailSet, mb, fmt.Sprintf("SEO morning check: %s, %d moved", site.URL, len(c.Moves)), c.Text(site.URL), time.Now())
|
||||
cancel()
|
||||
if err != nil {
|
||||
s.Log.Warn("seo: emailing the morning check", "err", err)
|
||||
continue
|
||||
}
|
||||
}
|
||||
if err := s.DB.PutJSON(checkEmailedKey(site.Property), c.To); err != nil {
|
||||
s.Log.Warn("seo: noting the morning check was sent", "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- The audit ---
|
||||
|
||||
var pageSpeedKey = secretField{"pagespeed", secrets.PageSpeedAPIKey, "PageSpeed Insights API key (optional)",
|
||||
|
||||
@@ -104,7 +104,7 @@ func TestSearchConsole(t *testing.T) {
|
||||
// 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"} {
|
||||
for _, want := range []string{"2026-11-04 to 2026-11-10", "/pricing/", "new", `class="chart line-chart"`, "<polyline class=\"this\""} {
|
||||
if !strings.Contains(body, want) {
|
||||
t.Errorf("check lacks %q", want)
|
||||
}
|
||||
@@ -123,8 +123,8 @@ func TestSearchConsole(t *testing.T) {
|
||||
}
|
||||
}
|
||||
// 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`) {
|
||||
postForm(h, "/settings/search", url.Values{"min_clicks": {"10"}, "min_positions": {"2.5"}, "min_impressions": {"500"}, "email_report": {"on"}, "email_check": {"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`) || !strings.Contains(body, `name="email_check" checked`) {
|
||||
t.Error("thresholds weren't saved")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/seo"
|
||||
)
|
||||
|
||||
// clickChart is the morning check's chart: clicks by day this week, as a
|
||||
// line, over the week before, as a fainter one, day for day.
|
||||
type clickChart struct {
|
||||
W, H int
|
||||
This, Prev string // polyline points
|
||||
Dots []chartDot
|
||||
Labels []chartLabel
|
||||
Max int
|
||||
MaxY int // where the top gridline is
|
||||
Empty bool
|
||||
}
|
||||
|
||||
type chartDot struct {
|
||||
X, Y float64
|
||||
Title string
|
||||
}
|
||||
|
||||
type chartLabel struct {
|
||||
X float64
|
||||
Text string
|
||||
}
|
||||
|
||||
const (
|
||||
chartW, chartH = 600, 170
|
||||
chartLeft = 28 // room for the scale
|
||||
chartTop = 10
|
||||
chartBottom = 22 // room for the days
|
||||
)
|
||||
|
||||
func newClickChart(this, prev []seo.Day) *clickChart {
|
||||
if len(this) == 0 {
|
||||
return nil
|
||||
}
|
||||
c := &clickChart{W: chartW, H: chartH, MaxY: chartTop}
|
||||
for _, d := range append(append([]seo.Day{}, this...), prev...) {
|
||||
c.Max = max(c.Max, d.Clicks)
|
||||
}
|
||||
c.Empty = c.Max == 0
|
||||
scale := max(c.Max, 1)
|
||||
n := len(this)
|
||||
x := func(i int) float64 {
|
||||
if n == 1 {
|
||||
return chartLeft + float64(chartW-chartLeft)/2
|
||||
}
|
||||
return chartLeft + 24 + float64(i)*float64(chartW-chartLeft-48)/float64(n-1)
|
||||
}
|
||||
y := func(v int) float64 {
|
||||
return chartTop + float64(chartH-chartTop-chartBottom)*(1-float64(v)/float64(scale))
|
||||
}
|
||||
points := func(days []seo.Day) string {
|
||||
var p []string
|
||||
for i, d := range days {
|
||||
if i < n {
|
||||
p = append(p, fmt.Sprintf("%.1f,%.1f", x(i), y(d.Clicks)))
|
||||
}
|
||||
}
|
||||
return strings.Join(p, " ")
|
||||
}
|
||||
c.This, c.Prev = points(this), points(prev)
|
||||
for i, d := range this {
|
||||
was := ""
|
||||
if i < len(prev) {
|
||||
was = fmt.Sprintf(" (%d the week before, on %s)", prev[i].Clicks, dayName(prev[i].Date))
|
||||
}
|
||||
c.Dots = append(c.Dots, chartDot{X: x(i), Y: y(d.Clicks), Title: fmt.Sprintf("%s: %d %s%s", dayName(d.Date), d.Clicks, clicksWord(d.Clicks), was)})
|
||||
c.Labels = append(c.Labels, chartLabel{X: x(i), Text: dayName(d.Date)})
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func dayName(date string) string {
|
||||
t, err := time.Parse("2006-01-02", date)
|
||||
if err != nil {
|
||||
return date
|
||||
}
|
||||
return t.Format("Mon 2")
|
||||
}
|
||||
|
||||
func clicksWord(n int) string {
|
||||
if n == 1 {
|
||||
return "click"
|
||||
}
|
||||
return "clicks"
|
||||
}
|
||||
@@ -393,6 +393,7 @@ func (s *Server) loadTemplates() error {
|
||||
"cls": func(x100 int) float64 { return float64(x100) / 100 },
|
||||
"dec1": func(f float64) string { return strconv.FormatFloat(f, 'f', 1, 64) },
|
||||
"pagePath": pagePath,
|
||||
"change": seo.Percent,
|
||||
"stage": signals.StageLabel,
|
||||
"channel": signals.ChannelLabel,
|
||||
"truncate": func(n int, s string) string {
|
||||
|
||||
@@ -465,3 +465,13 @@ input[type="color"] { height: 2.6rem; padding: 0.25rem; cursor: pointer; }
|
||||
.nav-row:not(.collapsed) .nav-sum { display: none; }
|
||||
.nav .nav-toggle:active { transform: none; }
|
||||
.nav .nav-toggle:disabled, .nav .nav-toggle:disabled:hover { opacity: 0.35; cursor: default; background: transparent; color: hsl(var(--muted-foreground)); }
|
||||
|
||||
/* The morning check's clicks by day: this week over the week before. */
|
||||
svg.line-chart polyline { fill: none; stroke-width: 2; stroke-linejoin: round; stroke-linecap: round; }
|
||||
svg.line-chart polyline.this { stroke: hsl(var(--primary)); }
|
||||
svg.line-chart polyline.prev { stroke: hsl(var(--muted-foreground)); stroke-dasharray: 4 4; opacity: 0.7; }
|
||||
svg.line-chart circle { fill: hsl(var(--primary)); }
|
||||
svg.line-chart line.axis { stroke: hsl(var(--border)); }
|
||||
.click-chart { margin: 0.5rem 0 0.75rem; }
|
||||
.click-chart .key { display: inline-block; width: 1.25rem; height: 0; vertical-align: middle; border-top: 2px solid hsl(var(--primary)); }
|
||||
.click-chart .key.prev { border-top: 2px dashed hsl(var(--muted-foreground)); }
|
||||
|
||||
@@ -209,3 +209,44 @@
|
||||
{{- else if eq .Status "removed"}}{{if .GoneAt.IsZero}}<span class="badge scheduled">removal merged, still on the site</span>{{else}}<span class="badge">removed</span>{{end}}
|
||||
{{- end}}{{if and .Error (ne .Status "failed")}} <span class="badge failed">to fix</span>{{end}}
|
||||
{{end}}
|
||||
|
||||
{{/* SEO: the morning check's chart, and the searches that gained and lost most (the check and the Monday report). */}}
|
||||
{{define "click-chart"}}
|
||||
<figure class="click-chart">
|
||||
<svg class="chart line-chart" viewBox="0 0 {{.W}} {{.H}}" role="img" aria-label="Clicks by day, this week against the week before">
|
||||
<text x="0" y="{{.MaxY}}" dominant-baseline="hanging">{{.Max}}</text><text x="0" y="148">0</text>
|
||||
<line class="axis" x1="28" y1="148" x2="{{.W}}" y2="148"></line>
|
||||
{{with .Prev}}<polyline class="prev" points="{{.}}"></polyline>{{end}}
|
||||
<polyline class="this" points="{{.This}}"></polyline>
|
||||
{{range .Dots}}<circle cx="{{.X}}" cy="{{.Y}}" r="3.5"><title>{{.Title}}</title></circle>{{end}}
|
||||
{{range .Labels}}<text x="{{.X}}" y="166" text-anchor="middle">{{.Text}}</text>{{end}}
|
||||
</svg>
|
||||
<figcaption class="small muted"><span class="key this"></span> clicks this week · <span class="key prev"></span> the week before, day for day</figcaption>
|
||||
</figure>
|
||||
{{end}}
|
||||
|
||||
{{define "query-changes"}}
|
||||
{{if or .Gains .Losses}}
|
||||
<div class="cols">
|
||||
{{template "query-list" dict "Title" "↑ Searches that gained most clicks" "List" .Gains}}
|
||||
{{template "query-list" dict "Title" "↓ Searches that lost most clicks" "List" .Losses}}
|
||||
</div>
|
||||
<p class="help">Every change counts in these two lists, however small: they're for a look. What really moved, past your thresholds, is listed on its own.</p>
|
||||
{{end}}
|
||||
{{end}}
|
||||
|
||||
{{define "query-list"}}
|
||||
<section class="card">
|
||||
<h3>{{.Title}}</h3>
|
||||
{{with .List}}
|
||||
<table class="list">
|
||||
<thead><tr><th>Search</th><th class="num">Clicks</th><th class="num">Position</th></tr></thead>
|
||||
<tbody>{{range .}}<tr>
|
||||
<td>{{.Query}}</td>
|
||||
<td class="num">{{num .Before.Clicks}} → <strong>{{if .NoData}}<span class="muted">no data</span>{{else}}{{num .After.Clicks}}{{end}}</strong></td>
|
||||
<td class="num">{{if .NoData}}{{dec1 .Before.Position}} → <span class="muted">no data</span>{{else if .New}}<span class="muted">new</span> {{dec1 .After.Position}}{{else}}{{dec1 .Before.Position}} → {{dec1 .After.Position}}{{end}}</td>
|
||||
</tr>{{end}}</tbody>
|
||||
</table>
|
||||
{{else}}<p class="help">None this week.</p>{{end}}
|
||||
</section>
|
||||
{{end}}
|
||||
|
||||
@@ -62,6 +62,7 @@
|
||||
<label>On at least <input name="min_impressions" inputmode="numeric" value="{{$s.MinImpressions}}" size="6"> impressions</label>
|
||||
</div>
|
||||
<label class="check"><input type="checkbox" name="email_report" {{if $s.EmailReport}}checked{{end}}> Email me the Monday report (through the mailbox under <a href="/settings/email">Settings → Email</a>)</label>
|
||||
<label class="check"><input type="checkbox" name="email_check" {{if $s.EmailCheck}}checked{{end}}> Email me the morning check when something really moved (at most once a day, when Search Console's data moves on)</label>
|
||||
</section>
|
||||
{{end}}
|
||||
|
||||
|
||||
@@ -12,9 +12,12 @@
|
||||
{{with .Check}}
|
||||
<section class="card">
|
||||
<p class="small muted">{{.From}} to {{.To}}, against {{.PrevFrom}} to {{.PrevTo}} · {{.Pages}} pages and {{.Queries}} searches compared</p>
|
||||
<p>Clicks <strong>{{num .Before.Clicks}} → {{num .After.Clicks}}</strong> · impressions {{num .Before.Impressions}} → {{num .After.Impressions}} · position {{dec1 .Before.Position}} → {{dec1 .After.Position}}</p>
|
||||
<p>Clicks <strong>{{num .Before.Clicks}} → {{num .After.Clicks}}</strong>{{with change .Before.Clicks .After.Clicks}} <span class="muted">({{.}})</span>{{end}} · impressions {{num .Before.Impressions}} → {{num .After.Impressions}}{{with change .Before.Impressions .After.Impressions}} <span class="muted">({{.}})</span>{{end}} · position {{dec1 .Before.Position}} → {{dec1 .After.Position}}</p>
|
||||
{{with $d.Chart}}{{template "click-chart" .}}{{end}}
|
||||
{{range .Outside}}<p class="small muted">{{.Sentence}}</p>{{end}}
|
||||
{{if .Quiet}}<p class="ok">Nothing real moved.</p>{{end}}
|
||||
</section>
|
||||
{{template "query-changes" .}}
|
||||
{{if not .Quiet}}
|
||||
<table class="list">
|
||||
<thead><tr><th>Page or search</th><th class="num">Clicks</th><th class="num">Impressions</th><th class="num">Position</th><th>What the data shows</th></tr></thead>
|
||||
@@ -37,3 +40,4 @@
|
||||
{{end}}
|
||||
{{end}}
|
||||
{{end}}{{end}}
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<form method="post" action="/seo/report?site={{.Current.Index}}" data-busy="Writing…"><button type="submit" class="secondary">Write it now</button></form>
|
||||
</div>{{end}}
|
||||
</div>
|
||||
<p class="lede">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}}.</p>
|
||||
<p class="lede">One page, the same every week, so this Monday compares with the last in seconds: three numbers, the searches that gained and lost most, 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}}.</p>
|
||||
|
||||
{{template "seo-sites" .}}
|
||||
{{if .Current}}
|
||||
@@ -14,12 +14,14 @@
|
||||
<p class="small muted">{{.WeekFrom}} to {{.WeekTo}}, against the week before · written {{ago .CreatedAt}}</p>
|
||||
<h2>1. The week</h2>
|
||||
<div class="funnel">
|
||||
<div class="step"><span class="label">Clicks</span><strong>{{num .After.Clicks}}</strong><span class="rate">was {{num .Before.Clicks}}</span></div>
|
||||
<div class="step"><span class="label">Impressions</span><strong>{{num .After.Impressions}}</strong><span class="rate">was {{num .Before.Impressions}}</span></div>
|
||||
<div class="step"><span class="label">Clicks</span><strong>{{num .After.Clicks}}</strong><span class="rate">was {{num .Before.Clicks}}{{with change .Before.Clicks .After.Clicks}} · {{.}}{{end}}</span></div>
|
||||
<div class="step"><span class="label">Impressions</span><strong>{{num .After.Impressions}}</strong><span class="rate">was {{num .Before.Impressions}}{{with change .Before.Impressions .After.Impressions}} · {{.}}{{end}}</span></div>
|
||||
<div class="step"><span class="label">Position</span><strong>{{dec1 .After.Position}}</strong><span class="rate">was {{dec1 .Before.Position}}</span></div>
|
||||
</div>
|
||||
<p>{{.Where}}</p>
|
||||
{{range .Outside}}<p class="small muted">{{.Sentence}}</p>{{end}}
|
||||
</section>
|
||||
{{template "query-changes" .}}
|
||||
|
||||
<section class="card">
|
||||
<h2>2. The pages that moved most</h2>
|
||||
|
||||
Reference in New Issue
Block a user