Files
supermarket/internal/seo/ranks.go
T
davidandClaude Opus 5.5 5ea620a091 Phase 3 part 1: Search Console and what already ranks
PLAN: Phase 3 rewritten around a weekly seven-job SEO loop (what ranks,
next keywords, brief, page, approval, morning check, Monday report),
with chatseo.app's ideas borrowed and rankings from Search Console only.

Google OAuth (PKCE, offline, read-only webmasters scope) from Settings →
Search engines, with each website's property. Search Console is synced
into SQLite by day (site, page, and page+query; 16 months, then twice a
day). SEO → What ranks shows the last 90 days: totals, the share of
clicks from hidden queries, best pages, queries shown but not clicked,
and the pages to protect and to push, each with its numbers. Schema 12.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 07:17:37 -07:00

248 lines
6.8 KiB
Go

package seo
import (
"database/sql"
"fmt"
"slices"
"strconv"
"strings"
"time"
"supermarket/internal/db"
)
// Numbers are a page's, a query's or a site's numbers over a period.
type Numbers struct {
Clicks int
Impressions int
Position float64 // average, weighted by impressions; 0 without impressions
}
// CTR is the click rate, in percent.
func (n Numbers) CTR() float64 {
if n.Impressions == 0 {
return 0
}
return 100 * float64(n.Clicks) / float64(n.Impressions)
}
func position(posSum float64, impressions int) float64 {
if impressions == 0 {
return 0
}
return posSum / float64(impressions)
}
// PageRow is a page and its numbers.
type PageRow struct {
Page string
Numbers
}
// QueryRow is a query and its numbers.
type QueryRow struct {
Query string
Numbers
}
// Pick is a page to protect or to push, with the numbers that justify it.
type Pick struct {
Page string
Numbers Numbers
MainQuery string // the query with the most impressions for the page
MainShare float64 // that query's share of the page's impressions, in percent
MainPos float64 // the page's position for it
Why string
}
// Ranks is job 1: what already ranks, over a period.
type Ranks struct {
Site string
From, To string
Total Numbers
Anonymous float64 // share of clicks from queries Google doesn't name, in percent; -1 if unknown
Pages []PageRow
Unclicked []QueryRow // shown a lot, almost never clicked
Protect []Pick
Push []Pick
}
// RanksDays is the period job 1 looks at.
const RanksDays = 90
// Thresholds for "pushing" a page: on page one, shown enough, rarely clicked.
const (
pushMaxPosition = 10.5
pushMinImpr = 100
lowCTR = 1.0 // percent
)
// period is the last n days up to the latest stored day.
func period(d *db.DB, site string, days int) (from, to string, ok bool) {
to = Through(d, site)
if to == "" {
return "", "", false
}
t, err := time.Parse(dayFormat, to)
if err != nil {
return "", "", false
}
return t.AddDate(0, 0, -(days - 1)).Format(dayFormat), to, true
}
// WhatRanks works out job 1 for a property, over the last RanksDays days
// of final data. It returns nil if nothing is stored yet.
func WhatRanks(d *db.DB, site string) (*Ranks, error) {
from, to, ok := period(d, site, RanksDays)
if !ok {
return nil, nil
}
r := &Ranks{Site: site, From: from, To: to, Anonymous: -1}
var posSum float64
if 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(&r.Total.Clicks, &r.Total.Impressions, &posSum); err != nil {
return nil, err
}
r.Total.Position = position(posSum, r.Total.Impressions)
var named int
if err := d.QueryRow(`SELECT coalesce(sum(clicks), 0) FROM gsc_query_days WHERE site = ? AND date BETWEEN ? AND ?`,
site, from, to).Scan(&named); err != nil {
return nil, err
}
if r.Total.Clicks > 0 {
r.Anonymous = 100 * float64(r.Total.Clicks-min(named, r.Total.Clicks)) / float64(r.Total.Clicks)
}
pages, err := pageNumbers(d, site, from, to)
if err != nil {
return nil, err
}
for i, p := range pages {
if i == 10 {
break
}
r.Pages = append(r.Pages, p)
}
rows, err := d.Query(`SELECT query, sum(clicks), sum(impressions), sum(pos_sum) FROM gsc_query_days
WHERE site = ? AND date BETWEEN ? AND ? GROUP BY query
HAVING sum(impressions) > 0 AND 100.0 * sum(clicks) / sum(impressions) < ?
ORDER BY sum(impressions) DESC LIMIT 10`, site, from, to, lowCTR)
if err != nil {
return nil, err
}
for rows.Next() {
var q QueryRow
var ps float64
if err := rows.Scan(&q.Query, &q.Clicks, &q.Impressions, &ps); err != nil {
rows.Close()
return nil, err
}
q.Position = position(ps, q.Impressions)
r.Unclicked = append(r.Unclicked, q)
}
rows.Close()
// Protect: the pages that carry the clicks.
for _, p := range pages {
if len(r.Protect) == 3 || p.Clicks == 0 {
break
}
pick := Pick{Page: p.Page, Numbers: p.Numbers}
pick.Why = fmt.Sprintf("%s clicks, %.1f%% of all clicks, at position %.1f.", Thousands(p.Clicks), share(p.Clicks, r.Total.Clicks), p.Position)
r.Protect = append(r.Protect, pick)
}
// Push: on page one, shown a lot, hardly clicked.
var cands []PageRow
for _, p := range pages {
if p.Position > 0 && p.Position <= pushMaxPosition && p.Impressions >= pushMinImpr && p.CTR() < lowCTR {
cands = append(cands, p)
}
}
slices.SortStableFunc(cands, func(a, b PageRow) int { return b.Impressions - a.Impressions })
for _, p := range cands {
if len(r.Push) == 3 {
break
}
pick := Pick{Page: p.Page, Numbers: p.Numbers}
if err := mainQuery(d, site, from, to, &pick); err != nil {
return nil, err
}
pick.Why = fmt.Sprintf("Shown %s times at position %.1f, %s %s.", Thousands(p.Impressions), p.Position, Thousands(p.Clicks), plural(p.Clicks, "click", "clicks"))
if pick.MainQuery != "" {
pick.Why += fmt.Sprintf(" %.0f%% of its impressions come from “%s”, where it's at %.1f.", pick.MainShare, pick.MainQuery, pick.MainPos)
}
r.Push = append(r.Push, pick)
}
return r, nil
}
// pageNumbers are every page's numbers over a period, most clicks first.
func pageNumbers(d *db.DB, site, from, to string) ([]PageRow, error) {
rows, err := d.Query(`SELECT page, sum(clicks), sum(impressions), sum(pos_sum) FROM gsc_page_days
WHERE site = ? AND date BETWEEN ? AND ? GROUP BY page ORDER BY sum(clicks) DESC, sum(impressions) DESC`, site, from, to)
if err != nil {
return nil, err
}
defer rows.Close()
var out []PageRow
for rows.Next() {
var p PageRow
var ps float64
if err := rows.Scan(&p.Page, &p.Clicks, &p.Impressions, &ps); err != nil {
return nil, err
}
p.Position = position(ps, p.Impressions)
out = append(out, p)
}
return out, rows.Err()
}
// mainQuery fills in the query a page is shown for most.
func mainQuery(d *db.DB, site, from, to string, p *Pick) error {
var q string
var impr int
var ps float64
err := d.QueryRow(`SELECT query, sum(impressions), sum(pos_sum) FROM gsc_query_days
WHERE site = ? AND page = ? AND date BETWEEN ? AND ? GROUP BY query ORDER BY sum(impressions) DESC LIMIT 1`,
site, p.Page, from, to).Scan(&q, &impr, &ps)
if err == sql.ErrNoRows {
return nil
}
if err != nil {
return err
}
p.MainQuery, p.MainShare, p.MainPos = q, share(impr, p.Numbers.Impressions), position(ps, impr)
return nil
}
func share(part, whole int) float64 {
if whole == 0 {
return 0
}
return 100 * float64(part) / float64(whole)
}
func plural(n int, one, many string) string {
if n == 1 {
return one
}
return many
}
// Thousands writes an integer with thousands separators: 63,201.
func Thousands(n int) string {
s := strconv.Itoa(n)
neg := strings.HasPrefix(s, "-")
s = strings.TrimPrefix(s, "-")
for i := len(s) - 3; i > 0; i -= 3 {
s = s[:i] + "," + s[i:]
}
if neg {
return "-" + s
}
return s
}