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>
This commit is contained in:
2026-11-22 07:17:37 -07:00
co-authored by Claude Opus 5.5
parent d23d5e2a87
commit 5ea620a091
19 changed files with 1590 additions and 31 deletions
+285
View File
@@ -0,0 +1,285 @@
package web
import (
"context"
"errors"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"time"
"supermarket/internal/api/gsc"
"supermarket/internal/oauth"
"supermarket/internal/profile"
"supermarket/internal/secrets"
"supermarket/internal/seo"
)
var googleFields = []secretField{
{"google", secrets.GoogleClientID, "OAuth client ID",
"In Google Cloud: create a project, enable the Google Search Console API, set up the OAuth consent screen (add yourself as a test user, or publish it so the sign-in doesn't expire after 7 days), then Credentials → Create credentials → OAuth client ID → Web application, with the redirect URI below.", googleCreds},
{"google", secrets.GoogleClientSecret, "OAuth client secret", "Shown next to the client ID.", googleCreds},
}
// gscBase is the Search Console API's address; tests point it elsewhere.
var gscBase = ""
// googleAuth caches the access token, which lasts an hour.
type googleAuth struct {
mu sync.Mutex
token string
expires time.Time
}
var gauth googleAuth
func (s *Server) setGoogleToken(res *oauth.Result) {
gauth.mu.Lock()
defer gauth.mu.Unlock()
gauth.token = res.AccessToken
life := res.ExpiresIn
if life <= 0 {
life = time.Hour
}
gauth.expires = time.Now().Add(life - time.Minute)
}
// googleToken returns an access token, refreshing it when it's run out.
func (s *Server) googleToken(ctx context.Context) (string, error) {
gauth.mu.Lock()
tok, exp := gauth.token, gauth.expires
gauth.mu.Unlock()
if tok != "" && time.Now().Before(exp) {
return tok, nil
}
refresh := s.Secrets.Get(secrets.GoogleRefreshToken)
if refresh == "" {
return "", errors.New("connect Search Console first, under Settings → Search engines")
}
res, err := oauth.RefreshGoogle(ctx, s.Secrets.Get(secrets.GoogleClientID), s.Secrets.Get(secrets.GoogleClientSecret), refresh)
if err != nil {
return "", errors.New("Google refused to renew the sign-in; connect Search Console again (" + err.Error() + ")")
}
s.setGoogleToken(res)
return res.AccessToken, nil
}
// gsc is a Search Console client, or nil when it isn't connected.
func (s *Server) gsc() *gsc.Client {
if !s.Secrets.Has(secrets.GoogleRefreshToken) {
return nil
}
c := gsc.New(s.googleToken)
if gscBase != "" {
c.WithBase(gscBase)
}
return c
}
// seoSite is a website and its Search Console property.
type seoSite struct {
Index int
URL string
Property string
Last *seo.SyncResult
}
func (s *Server) seoSites() []seoSite {
p, _ := profile.Load(s.DB)
if p == nil {
return nil
}
var out []seoSite
for i, w := range p.Websites {
site := seoSite{Index: i, URL: w.URL, Property: w.SearchConsoleProperty}
if site.Property != "" {
site.Last, _ = seo.LastSync(s.DB, site.Property)
}
out = append(out, site)
}
return out
}
// --- Settings → Search engines ---
func (s *Server) searchSettingsPage(w http.ResponseWriter, r *http.Request) {
s.renderSearchSettings(w, r, "")
}
func (s *Server) renderSearchSettings(w http.ResponseWriter, r *http.Request, errMsg string) {
data := map[string]any{
"Fields": googleFields,
"Set": s.secretState(secrets.GoogleClientID, secrets.GoogleClientSecret, secrets.GoogleRefreshToken),
"Redirect": s.callbackURL("google"),
"Sites": s.seoSites(),
"Connected": s.Secrets.Has(secrets.GoogleRefreshToken),
"Account": s.connections()["google"].Account,
}
if c := s.gsc(); c != nil {
ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
props, err := c.Sites(ctx)
cancel()
if err != nil {
data["PropsError"] = err.Error()
}
data["Properties"] = props
}
s.render(w, r, "search-engines", page{Title: "Search engines", Nav: "settings/search", Error: errMsg, Data: data})
}
func (s *Server) searchSettingsSave(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err := s.saveSecrets(r, googleFields); err != nil {
s.serverError(w, err)
return
}
if r.PostForm.Get("remove:"+secrets.GoogleRefreshToken) == "on" {
if err := s.Secrets.Set(map[string]string{secrets.GoogleRefreshToken: ""}); err != nil {
s.serverError(w, err)
return
}
gauth.mu.Lock()
gauth.token = ""
gauth.mu.Unlock()
}
if props, has := r.PostForm["property"]; has {
p, err := profile.Load(s.DB)
if err != nil {
s.serverError(w, err)
return
}
for i := range p.Websites {
if i < len(props) {
p.Websites[i].SearchConsoleProperty = strings.TrimSpace(props[i])
}
}
if err := profile.Save(s.DB, p); err != nil {
s.serverError(w, err)
return
}
}
redirect(w, r, "/settings/search", "saved")
}
// seoSync syncs every website's property now.
func (s *Server) seoSync(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Minute)
defer cancel()
if err := s.syncSearchConsole(ctx); err != nil {
s.renderSearchSettings(w, r, "Syncing: "+err.Error())
return
}
back := r.PostFormValue("back")
if !strings.HasPrefix(back, "/") || strings.HasPrefix(back, "//") {
back = "/settings/search"
}
redirect(w, r, back, "synced")
}
func (s *Server) syncSearchConsole(ctx context.Context) error {
c := s.gsc()
if c == nil {
return errors.New("connect Search Console first")
}
var errs []string
n := 0
for _, site := range s.seoSites() {
if site.Property == "" {
continue
}
n++
if _, err := seo.Sync(ctx, s.DB, c, site.Property, time.Now()); err != nil {
errs = append(errs, site.Property+": "+err.Error())
}
}
if n == 0 {
return errors.New("choose a Search Console property for a website first")
}
if len(errs) > 0 {
return errors.New(strings.Join(errs, "; "))
}
return nil
}
// RunSEO syncs Search Console twice a day.
func (s *Server) RunSEO(ctx context.Context) {
tick := time.NewTicker(30 * time.Minute)
defer tick.Stop()
for {
if s.gsc() != nil {
due := false
for _, site := range s.seoSites() {
if site.Property != "" && (site.Last == nil || time.Since(site.Last.At) > 12*time.Hour) {
due = true
}
}
if due {
sctx, cancel := context.WithTimeout(ctx, 30*time.Minute)
if err := s.syncSearchConsole(sctx); err != nil {
s.Log.Warn("seo: Search Console sync", "err", err)
}
cancel()
}
}
select {
case <-ctx.Done():
return
case <-tick.C:
}
}
}
// --- 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,
}
if cur != nil {
ranks, err := seo.WhatRanks(s.DB, cur.Property)
if err != nil {
s.serverError(w, err)
return
}
data["Ranks"] = ranks
}
s.render(w, r, "seo", page{Title: "SEO", Nav: "seo/ranks", Data: data})
}
// pagePath shows a page's address without the site, for tables.
func pagePath(u string) string {
p, err := url.Parse(u)
if err != nil || p.Path == "" {
return u
}
if p.RawQuery != "" {
return p.Path + "?" + p.RawQuery
}
return p.Path
}