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

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

270 lines
8.5 KiB
Go

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"`
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"`
}
// 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, sc Scope, now time.Time) (*Report, error) {
c, err := MorningCheck(d, sc, Settings{}) // every change, to rank the pages
if err != nil || c == nil {
return nil, err
}
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) {
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, sc, LoadSettings(d))
if err != nil {
return nil, err
}
for i := range pages {
pages[i].Why = []string{"Under the thresholds for a real move: noise until it lasts."}
for _, m := range full.Moves {
if m.Kind == "page" && m.Key == pages[i].Key {
pages[i].Why = m.Why
}
}
}
r.Pages = pages
// The changes proposed for the site, or else the pages to push.
rows, err := d.Query(`SELECT `+changeCols+` FROM seo_changes WHERE property = ? AND status = ? ORDER BY id LIMIT ?`,
sc.Property, ChangeProposed, MaxWaiting)
if err != nil {
return nil, err
}
proposed, err := scanChanges(rows)
if err != nil {
return nil, err
}
for _, c := range proposed {
var what []string
if c.NewTitle != "" {
what = append(what, fmt.Sprintf("New title: “%s” (%d characters, about %d px).", c.NewTitle, c.NewTitleChars(), c.NewTitlePixels()))
}
if c.NewDescription != "" {
what = append(what, fmt.Sprintf("New description: “%s”.", c.NewDescription))
}
r.Waiting = append(r.Waiting, Pick{Page: c.Page, Why: strings.Join(what, " ") + " Why: " + c.Why})
}
// With nothing proposed, the pages worth a proposal, kept apart: they
// aren't waiting for a yes until a change is proposed for them.
if len(r.Waiting) == 0 {
ranks, err := WhatRanks(d, sc)
if err != nil {
return nil, err
}
if ranks != nil {
r.Candidates = 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%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", 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")
}
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 is waiting: no change has been proposed.\n")
}
for i, p := range r.Waiting {
fmt.Fprintf(&b, " %d. %s\n %s\n", i+1, p.Page, p.Why)
}
if len(r.Candidates) > 0 {
b.WriteString("\n Worth a proposal (Propose changes, on SEO → Changes):\n")
for _, p := range r.Candidates {
fmt.Fprintf(&b, " - %s\n %s\n", p.Page, p.Why)
}
}
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())
}
}