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
+157 -18
View File
@@ -32,7 +32,7 @@ running a Federated Core can install as a CoreDesktop sibling.
| Create and send content to X, LinkedIn, Reddit | Phase 1: Content module, built on today's pipeline, + Reddit |
| Find prospects → EspoCRM via Core MCP | Phase 2: Prospects module; CRM writes go through Hermes |
| SEO suggestions, change the Hugo repo | Phase 3: SEO module, with changes opened as PRs on Gitea |
| SEO for Google, Brave, DuckDuckGo | Phase 3: Search Console, Bing Webmaster + IndexNow (DuckDuckGo results come mostly from Bing), Brave Search API for rank tracking |
| SEO for Google, Brave, DuckDuckGo | Phase 3: Search Console, Bing Webmaster + IndexNow (DuckDuckGo results come mostly from Bing); rankings from Search Console (decided 2026-11-22) |
| Top-of-funnel lead generation | Content + SEO + prospecting + landing-page forms that create EspoCRM Leads |
| Pipeline influence, CAC, CLV, NRR | Phase 4: Metrics module (Stripe + EspoCRM via Hermes + Plausible) |
| Website, components | Phase 5: Sites module and component library |
@@ -658,22 +658,161 @@ Inbound: the lead-form component (Phase 5) queues a Lead the same way,
tagged with the signal from its UTM campaign.
### Phase 3: SEO, for all of the company's websites
1. Audit each website: titles, meta descriptions, headings, canonical URLs,
sitemap, robots.txt, JSON-LD, Open Graph, broken links, alt text, Core Web
Vitals (PageSpeed Insights API).
2. Content gaps: the profile's keywords and the competitors' sites from the
Inventory, compared with ours.
3. Search engines: Google Search Console API, Bing Webmaster API, IndexNow on
publish, and Brave Search API rank tracking.
4. Apply fixes: clone the site's Gitea repo into `/data/sites/`, make the
changes on a branch, check that `hugo` still builds, show the diff in the
UI, and open a PR on Gitea. Nothing is pushed to the default branch.
Merging the PR is the user's decision, and their hooks publish it.
5. Before/after tracking for each change.
6. **Reminder (asked 2026-11-21): review chatseo.app** before designing
this phase: what it does, what we could learn from it or connect to, and
whether it overlaps with the steps above. Raise it with the user when
Phase 3 starts.
**Started 2026-11-22** on branch `phase3-seo`, after Phase 2 was merged
into `main`.
**Decisions (the user, 2026-11-22).**
- **chatseo.app:** borrow its ideas only, no subscription. It was reviewed
as the reminder asked. It's a paid chat-based SEO agent (from €39 a
month; MCP and API from €59) built on Search Console, DataForSEO and its
own crawler. Two ideas are worth taking: rank every issue by its Search
Console impressions and clicks, and check whether AI assistants can read
and cite the site.
- **Rankings come from Search Console only**: Google's own position per
query and page, free. There is no keyword-volume or SERP data provider.
Where the live top results matter (a brief, a keyword's competition),
they're read with Claude's web search, which costs searches, only when
the user asks.
- **The workflow follows a "full lifecycle" post** (@thwlf67, 18 Nov 2026,
saved by the user as a PDF). SEO for a small site is seven jobs that
come back every week: find what already ranks, find the next keywords,
write a brief, write the page, approve and publish, check Search Console
every morning, and write the Monday report. Supermarket does six of them;
the user keeps the approval. Its rules become the module's rules:
- Every number comes from the data, and none is invented: when a source
returns nothing, the report says "no data", not zero.
- Every recommendation carries the number that justifies it.
- Thresholds decide what's worth reporting, and "nothing real moved" is a
one-line answer.
- One job at a time, each with its own definition of done.
- Nothing changes on a site without the user's yes, given one change at a
time, never in bulk; at most 3 recommendations a week.
- Pages never claim tests or experience that didn't happen. A brief ends
with the questions only the user can answer, and the draft is written
around their answers, with what wasn't tested said plainly.
- The weekly report has a fixed format, so this Monday compares with the
last in seconds.
- Numbers are computed in code, from Search Console. The AI writes words
around them (titles, briefs, pages, the reasons in a report) and never
produces a number itself.
**Parts, in order, a commit after each:**
1. **Search Console and "what already ranks" (job 1).**
- Connect Google with OAuth (read-only `webmasters.readonly`), from
Settings. Choose the property for each website in the profile.
- Sync daily rows by page and query (and page alone, since Google hides
some queries) into SQLite. Start with 16 months of history, then the
latest final days. Search Console data is 2 to 3 days late, and the
app says so.
- An SEO page per site, showing:
- The 90-day totals and click rate.
- The best pages by clicks.
- The queries Google shows most where almost nobody clicks.
- The pages to **protect** (they carry the clicks) and to **push**
(they rank on page one and don't get clicked), each with the number
that justifies it.
- The share of clicks from queries Google doesn't name.
- **Built 2026-11-22** (schema 12):
- `oauth.GoogleStart` (PKCE, offline access) and `internal/api/gsc`
(sites and search analytics, paged at 25,000 rows).
- `internal/seo`: `Sync` reads 30-day chunks of date, date+page and
date+page+query rows. Position is stored × impressions. The last 4
days are re-read each time.
- `WhatRanks` computes job 1 over 90 days. *Protect* is the top 3
pages by clicks. *Push* is page-one pages (position ≤ 10.5) with at
least 100 impressions and under 1% click rate, each with its main
query and that query's share.
- 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.
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:
more than 5 clicks, or more than 3 positions on at least 300
impressions; both editable). Otherwise it says one line.
- Each move is explained where the data allows. The key case is "the
page didn't lose its ranking, Google showed its big query less, so
the average moved", found by splitting a page's position change by
query. A query that vanished is "no data", not a drop to zero.
- **Monday report**, on one page and the same every week:
1. Clicks, impressions and position, against the week before, with a
sentence on where the change came from: visibility, or rank and
click rate.
2. The 3 pages that moved most.
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.
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:
- title and meta description (length in characters and pixels)
- H1 and heading order
- canonical, hreflang and noindex
- status, redirects and broken links
- images without alt text
- Open Graph and JSON-LD
- sitemap and robots.txt coverage
- Optionally, Core Web Vitals from the PageSpeed Insights API.
- Every issue is ranked by the page's Search Console impressions and
clicks, so a fix list starts with the pages that bring traffic.
- **AI visibility:** whether robots.txt lets AI crawlers in (GPTBot,
ClaudeBot, PerplexityBot, Google-Extended…), an `llms.txt`,
structured data, and pages readable without JavaScript.
- One more check, from job 3: a page's biggest query compared with its
title. When they don't say the same thing, that's the cheapest fix
there is.
4. **Changes, approval and pull requests (job 5), with before/after.**
- The AI proposes the exact change: a title, a meta description or an
H1. Each one comes with the number that pays for it and the title's
length in characters and pixels.
- The user says yes or no, one change at a time.
- A yes clones the site's Gitea repository into `/data/sites/` and
edits the page's front matter or content on a branch. It checks that
`hugo` still builds, shows the diff, and opens a pull request.
Nothing is pushed to the default branch, and merging is the user's
decision.
- Once merged and live, the change is checked on the site and pinged
with IndexNow. Its page's clicks, impressions and position are then
compared over the weeks before and after (PLAN item "before/after
tracking"). The morning check notices when a yes changed something.
5. **The next keywords (job 2).**
- Candidates come from four places:
- Search Console queries with impressions and no page that answers
them.
- The profile's keywords and targets.
- The signals' "How to spot it" lines.
- Content gaps against competitors' sites in the Inventory, from
their sitemaps and titles.
- Each candidate is checked against our own pages ("no page" must
really mean no page).
- On request, Claude's web search reads who holds the live top 3. A
keyword is ranked by who has to be beaten, not by volume; volume and
difficulty aren't available and say "not available".
- Pick one a month.
6. **Briefs and pages (jobs 3 and 4).**
- A brief starts from what the page is really shown for in Search
Console, then the live top 5 (read with web search, and "couldn't
read" said where a fetch failed).
- It gives the title, meta description, H1, the sections in order, the
questions the page must answer, and 3 internal links to existing
pages.
- It ends with questions only the user can answer.
- From the brief and the user's answers, a draft page or rewrite is
written into the Hugo site as a pull request. The draft goes through
a check that underlines every sentence claiming an experience ("we
tried", "in our test") for the user to confirm.
- Pages can be tagged with a buying signal (Phase 2's campaign tags), so
landing pages count on its scorecard.
7. **Bing and IndexNow:**
- Bing Webmaster's API, for Bing's queries and crawl problems.
- IndexNow on every merge.
- The Search Console sitemap status.
Before the first part: a Google Cloud project with the Search Console API
turned on and an OAuth client (redirect
`http://localhost:8470/auth/google/callback`), and a Gitea token with access
to each site's repository (needed from part 4).
### Phase 4: Metrics, with Stripe
@@ -820,7 +959,7 @@ Phase 0 (incl. Hermes bridge test) ──► Phase 1 (content)
│
├──► Phase 2 (signals, prospects, funnel) ── needs: Hermes bridge, mcphub EspoCRM tools,
│ mail on the Core, Plausible, Stripe key
├──► Phase 3 (SEO) ──────── needs: Gitea token
├──► Phase 3 (SEO) ──────── needs: Google OAuth (Search Console), Gitea token
├──► Phase 4 (metrics) ──── needs: Stripe key; CRM reads for pipeline
└──► Phase 5 (sites) ────── needs: Gitea token
```
+2
View File
@@ -104,6 +104,8 @@ To check the connection, open **Core & Hermes** in Supermarket and ask Hermes th
**Outreach (Prospects → Outreach, and Settings → Email).** On Review, *Write an email* or *Write a LinkedIn message* on a person has the AI draft one from their buying signal's hypothesis and angle, what's known about them and their company, and anything that happened before (an earlier reply, or a message you sent). *Draft* on the Outreach page does the same for up to 5 accepted people nobody has written to yet. Read and edit every draft. An email you *queue* goes out through your Core's mail server (mail.<your domain>, set up under Settings → Email): one at a time, at least a few minutes apart, within your sending hours and daily limit (20 by default), with your signature and an opt-out line under it, links to your sites tagged with the signal's campaign, and a copy in your Sent folder. Nothing goes to a suppressed address, an address that bounces, or someone emailed in the last two weeks. LinkedIn can't be automated: copy the message, open their profile, send it there and *Mark as sent*. Every 10 minutes Supermarket reads the inbox, read-only, for replies (matched to the email they answer, or by sender), bounces (the address is marked as bouncing) and requests to stop (the address goes on the suppression list); out-of-office replies are ignored. Sent messages count as Contacted and replies as Replied on the signal's scorecard. *Check the settings* signs in to both servers and looks up your domain's SPF, DKIM and DMARC records.
**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.
**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.
+23 -3
View File
@@ -274,19 +274,39 @@ Throughout, also notice:
person who booked (after the next inbox read). A cancellation
doesn't count.
## 7. Search
## 7. SEO
### Search Console and what already ranks
- [ ] Under Settings → Search engines, after saving the Google OAuth client
ID and secret, *Connect Search Console* opens Google's sign-in and
comes back saying it's connected, with your account's email.
- [ ] Each website from the profile has a list of your Search Console
properties; choosing one and saving keeps it.
- [ ] *Sync now* reads the data (the first time can take a minute) and shows
when it synced and the last day of data.
- [ ] SEO → What ranks shows the last 90 days: compare clicks, impressions
and position with Search Console's own Performance report for the
same dates. They should match.
- [ ] The best pages and the "shown a lot, hardly clicked" searches match
Search Console's Pages and Queries tabs.
- [ ] Each page under *Push* really sits on page one with few clicks, and
the search it names is the one it's shown for most.
- [ ] With several websites, the tabs switch between them.
## 8. Search
- [ ] Searching for an inventory entry, a fetched item, a post, a prospect
(company or person) or a signal finds it, with a link to where it is.
## 8. Agents (MCP)
## 9. Agents (MCP)
- [ ] `supermarket token` prints a token.
- [ ] Claude Code (`claude mcp list`) shows Supermarket connected, and can
list prospects or the CRM queue through it.
- [ ] Hermes uses the Supermarket and Core MCP tools in its CRM job.
## 9. Data and safety
## 10. Data and safety
- [ ] `~/.local/share/supermarket/secrets.json` is readable only by you
(`ls -l`), and no key is ever shown in the app after saving.
+1
View File
@@ -160,6 +160,7 @@ func run(log *slog.Logger) error {
go srv.RunDiscovery(ctx)
go srv.RunOutreach(ctx)
go srv.RunTracking(ctx)
go srv.RunSEO(ctx)
// A sync falls due, and a claim times out, without anything being
// written: refresh the state file each minute.
go func() {
+156
View File
@@ -0,0 +1,156 @@
// Package gsc reads Google Search Console (the Search Console API v3,
// https://developers.google.com/webmaster-tools/v1/api_reference_index):
// the properties the signed-in account can see, and their search
// analytics. It only reads.
package gsc
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
)
const apiBase = "https://www.googleapis.com/webmasters/v3"
// ErrUnauthorized means Google refused the token: sign in again.
var ErrUnauthorized = errors.New("Google refused the sign-in: connect Search Console again")
// TokenFunc returns a current access token.
type TokenFunc func(ctx context.Context) (string, error)
// Client calls the API with tokens from a TokenFunc.
type Client struct {
token TokenFunc
base string
http *http.Client
}
func New(token TokenFunc) *Client {
return &Client{token: token, base: apiBase, http: &http.Client{Timeout: 2 * time.Minute}}
}
// WithBase points the client at another server (for tests).
func (c *Client) WithBase(u string) *Client {
c.base = strings.TrimRight(u, "/")
return c
}
func (c *Client) do(ctx context.Context, method, path string, body, out any) error {
tok, err := c.token(ctx)
if err != nil {
return err
}
var rd io.Reader
if body != nil {
raw, err := json.Marshal(body)
if err != nil {
return err
}
rd = bytes.NewReader(raw)
}
req, err := http.NewRequestWithContext(ctx, method, c.base+path, rd)
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+tok)
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
res, err := c.http.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
raw, err := io.ReadAll(io.LimitReader(res.Body, 64<<20))
if err != nil {
return err
}
if res.StatusCode == http.StatusUnauthorized {
return ErrUnauthorized
}
if res.StatusCode != http.StatusOK {
var e struct {
Error struct {
Message string `json:"message"`
} `json:"error"`
}
if json.Unmarshal(raw, &e) == nil && e.Error.Message != "" {
return fmt.Errorf("Search Console: %s", e.Error.Message)
}
return fmt.Errorf("Search Console: HTTP %d", res.StatusCode)
}
return json.Unmarshal(raw, out)
}
// Site is a property the account can read.
type Site struct {
URL string `json:"siteUrl"` // "sc-domain:example.com" or "https://example.com/"
Permission string `json:"permissionLevel"`
}
// Sites lists the properties the account can see.
func (c *Client) Sites(ctx context.Context) ([]Site, error) {
var out struct {
Entries []Site `json:"siteEntry"`
}
if err := c.do(ctx, http.MethodGet, "/sites", nil, &out); err != nil {
return nil, err
}
var usable []Site
for _, s := range out.Entries {
if s.Permission != "siteUnverifiedUser" {
usable = append(usable, s)
}
}
return usable, nil
}
// Query is a Search Analytics query.
type Query struct {
StartDate string `json:"startDate"` // YYYY-MM-DD
EndDate string `json:"endDate"`
Dimensions []string `json:"dimensions,omitempty"` // date, page, query, country, device
Type string `json:"type,omitempty"` // web (default)
RowLimit int `json:"rowLimit,omitempty"` // up to 25000
StartRow int `json:"startRow,omitempty"`
DataState string `json:"dataState,omitempty"` // final (default) or all
}
// Row is one result: the dimensions' values in order, and the numbers.
type Row struct {
Keys []string `json:"keys"`
Clicks float64 `json:"clicks"`
Impressions float64 `json:"impressions"`
CTR float64 `json:"ctr"`
Position float64 `json:"position"`
}
// maxRows is Google's page size.
const maxRows = 25000
// Analytics runs a query, reading every page of rows.
func (c *Client) Analytics(ctx context.Context, site string, q Query) ([]Row, error) {
path := "/sites/" + url.PathEscape(site) + "/searchAnalytics/query"
q.RowLimit = maxRows
var all []Row
for {
var out struct {
Rows []Row `json:"rows"`
}
if err := c.do(ctx, http.MethodPost, path, q, &out); err != nil {
return nil, err
}
all = append(all, out.Rows...)
if len(out.Rows) < maxRows {
return all, nil
}
q.StartRow += maxRows
}
}
+34
View File
@@ -360,6 +360,40 @@ CREATE TABLE stripe_customers (
utm_medium TEXT NOT NULL DEFAULT '',
first_seen TEXT NOT NULL
);
`,
// 12: Search Console, by day: the property's totals, each page's, and
// each page and query's (Google leaves out the queries it hides, so the
// page totals are kept apart). Position is stored as position ×
// impressions, so averages over days weigh by impressions.
`
CREATE TABLE gsc_site_days (
site TEXT NOT NULL, -- the Search Console property
date TEXT NOT NULL, -- YYYY-MM-DD
clicks INTEGER NOT NULL,
impressions INTEGER NOT NULL,
pos_sum REAL NOT NULL,
PRIMARY KEY (site, date)
);
CREATE TABLE gsc_page_days (
site TEXT NOT NULL,
date TEXT NOT NULL,
page TEXT NOT NULL,
clicks INTEGER NOT NULL,
impressions INTEGER NOT NULL,
pos_sum REAL NOT NULL,
PRIMARY KEY (site, date, page)
);
CREATE TABLE gsc_query_days (
site TEXT NOT NULL,
date TEXT NOT NULL,
page TEXT NOT NULL,
query TEXT NOT NULL,
clicks INTEGER NOT NULL,
impressions INTEGER NOT NULL,
pos_sum REAL NOT NULL,
PRIMARY KEY (site, date, page, query)
);
CREATE INDEX gsc_query_days_by_query ON gsc_query_days (site, query, date);
`,
}
+100 -2
View File
@@ -1,5 +1,5 @@
// Package oauth runs the OAuth 2.0 authorization-code flows for X and
// LinkedIn. The web app sends the browser to AuthURL, and its callback
// Package oauth runs the OAuth 2.0 authorization-code flows for X,
// LinkedIn, Reddit and Google. The web app sends the browser to AuthURL, and its callback
// handler calls Exchange with the code the provider sends back.
package oauth
@@ -254,3 +254,101 @@ func randomString() (string, error) {
}
return base64.RawURLEncoding.EncodeToString(b), nil
}
// --- Google (Search Console) ---
var (
googleAuthURL = "https://accounts.google.com/o/oauth2/v2/auth"
googleTokenURL = "https://oauth2.googleapis.com/token"
)
// GoogleScopes: read-only Search Console, and the account's email to show
// who is signed in.
const GoogleScopes = "https://www.googleapis.com/auth/webmasters.readonly openid email"
// GoogleStart begins Google's authorization-code flow with PKCE, asking for
// a refresh token (offline access) so the daily sync runs on its own.
func GoogleStart(clientID, redirectURI string) (string, *Pending, error) {
verifier, challenge, err := pkce()
if err != nil {
return "", nil, err
}
state, err := randomString()
if err != nil {
return "", nil, err
}
params := url.Values{
"response_type": {"code"},
"client_id": {clientID},
"redirect_uri": {redirectURI},
"scope": {GoogleScopes},
"state": {state},
"code_challenge": {challenge},
"code_challenge_method": {"S256"},
"access_type": {"offline"},
"prompt": {"consent"}, // always return a refresh token
}
p := &Pending{Provider: "google", State: state, Verifier: verifier, RedirectURI: redirectURI, Started: time.Now()}
return googleAuthURL + "?" + params.Encode(), p, nil
}
// GoogleExchange swaps the callback's code for tokens.
func GoogleExchange(ctx context.Context, clientID, clientSecret, code string, p *Pending) (*Result, error) {
return googleToken(ctx, url.Values{
"grant_type": {"authorization_code"},
"code": {code},
"redirect_uri": {p.RedirectURI},
"code_verifier": {p.Verifier},
"client_id": {clientID},
"client_secret": {clientSecret},
})
}
// RefreshGoogle gets a new access token (good for an hour) from the refresh
// token.
func RefreshGoogle(ctx context.Context, clientID, clientSecret, refreshToken string) (*Result, error) {
return googleToken(ctx, url.Values{
"grant_type": {"refresh_token"},
"refresh_token": {refreshToken},
"client_id": {clientID},
"client_secret": {clientSecret},
})
}
func googleToken(ctx context.Context, data url.Values) (*Result, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodPost, googleTokenURL, strings.NewReader(data.Encode()))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
return tokenResponse(req)
}
var googleUserInfoURL = "https://openidconnect.googleapis.com/v1/userinfo"
// GoogleEmail is the signed-in account's email.
func GoogleEmail(ctx context.Context, accessToken string) (string, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, googleUserInfoURL, nil)
if err != nil {
return "", err
}
req.Header.Set("Authorization", "Bearer "+accessToken)
res, err := httpClient.Do(req)
if err != nil {
return "", err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return "", fmt.Errorf("userinfo HTTP %d", res.StatusCode)
}
var out struct {
Email string `json:"email"`
}
err = json.NewDecoder(res.Body).Decode(&out)
return out.Email, err
}
// SetGoogleURLs points the Google flow at other servers (for tests).
func SetGoogleURLs(auth, token, userinfo string) {
googleAuthURL, googleTokenURL, googleUserInfoURL = auth, token, userinfo
}
+4
View File
@@ -39,6 +39,10 @@ const (
MailPassword = "mail.password" // the outreach mailbox on the Core
GoogleClientID = "google.client_id"
GoogleClientSecret = "google.client_secret"
GoogleRefreshToken = "google.refresh_token" // Search Console, read-only
PlausibleAPIKey = "plausible.api_key"
StripeAPIKey = "stripe.api_key" // restricted, read-only
+247
View File
@@ -0,0 +1,247 @@
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
}
+136
View File
@@ -0,0 +1,136 @@
package seo
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"testing"
"time"
"supermarket/internal/api/gsc"
"supermarket/internal/db"
)
func openDB(t *testing.T) *db.DB {
t.Helper()
d, err := db.Open(filepath.Join(t.TempDir(), "app.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { d.Close() })
return d
}
var now = time.Date(2026, 11, 22, 8, 0, 0, 0, time.UTC)
// fakeGSC answers like Search Console for one property, with data through
// 2026-11-19. Every day: the home page gets 10 clicks of 100 impressions at
// position 2; /bulking is shown 200 times at position 7.6 for "whey price
// comparison" and 20 times for "bulking whey", with no clicks; Google hides
// queries worth 2 home clicks a day.
func fakeGSC(t *testing.T, calls *[]gsc.Query) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "Bearer tok" {
w.WriteHeader(http.StatusUnauthorized)
return
}
if r.URL.Path == "/sites" {
json.NewEncoder(w).Encode(map[string]any{"siteEntry": []any{
map[string]any{"siteUrl": "sc-domain:whey.example", "permissionLevel": "siteOwner"},
map[string]any{"siteUrl": "https://other.example/", "permissionLevel": "siteUnverifiedUser"},
}})
return
}
if !strings.HasSuffix(r.URL.Path, "/searchAnalytics/query") || !strings.Contains(r.URL.RawPath+r.URL.Path, "sc-domain") {
t.Errorf("unexpected %s", r.URL)
}
var q gsc.Query
json.NewDecoder(r.Body).Decode(&q)
*calls = append(*calls, q)
start, _ := time.Parse(dayFormat, q.StartDate)
end, _ := time.Parse(dayFormat, q.EndDate)
if last, _ := time.Parse(dayFormat, "2026-11-19"); end.After(last) {
end = last
}
var rows []gsc.Row
home, bulk := "https://whey.example/", "https://whey.example/bulking/"
for d := start; !d.After(end); d = d.AddDate(0, 0, 1) {
day := d.Format(dayFormat)
switch strings.Join(q.Dimensions, ",") {
case "date":
rows = append(rows, gsc.Row{Keys: []string{day}, Clicks: 10, Impressions: 320, Position: 5.5})
case "date,page":
rows = append(rows, gsc.Row{Keys: []string{day, home}, Clicks: 10, Impressions: 100, Position: 2},
gsc.Row{Keys: []string{day, bulk}, Clicks: 0, Impressions: 220, Position: 7.6})
case "date,page,query":
rows = append(rows, gsc.Row{Keys: []string{day, home, "whey"}, Clicks: 8, Impressions: 90, Position: 2},
gsc.Row{Keys: []string{day, bulk, "whey price comparison"}, Clicks: 0, Impressions: 200, Position: 7.6},
gsc.Row{Keys: []string{day, bulk, "bulking whey"}, Clicks: 0, Impressions: 20, Position: 12})
}
}
json.NewEncoder(w).Encode(map[string]any{"rows": rows})
}))
}
func TestSyncAndWhatRanks(t *testing.T) {
d := openDB(t)
var calls []gsc.Query
srv := fakeGSC(t, &calls)
defer srv.Close()
c := gsc.New(func(context.Context) (string, error) { return "tok", nil }).WithBase(srv.URL)
sites, err := c.Sites(context.Background())
if err != nil || len(sites) != 1 || sites[0].URL != "sc-domain:whey.example" {
t.Fatalf("sites: %+v %v", sites, err)
}
if r, _ := WhatRanks(d, "sc-domain:whey.example"); r != nil {
t.Error("ranks before any data")
}
res, err := Sync(context.Background(), d, c, "sc-domain:whey.example", now)
if err != nil {
t.Fatal(err)
}
if res.Through != "2026-11-19" || res.From != "2025-07-30" || len(calls) != 3*17 {
t.Fatalf("sync: %+v, %d calls", res, len(calls))
}
// The next sync reads only the last days again.
calls = nil
res, _ = Sync(context.Background(), d, c, "sc-domain:whey.example", now.AddDate(0, 0, 1))
if res.From != "2026-11-15" || len(calls) != 3 || calls[0].DataState != "final" {
t.Errorf("second sync: %+v %+v", res, calls)
}
if last, _ := LastSync(d, "sc-domain:whey.example"); last == nil || last.Through != "2026-11-19" {
t.Errorf("last sync: %+v", last)
}
r, err := WhatRanks(d, "sc-domain:whey.example")
if err != nil {
t.Fatal(err)
}
if r.From != "2026-08-22" || r.To != "2026-11-19" || r.Total.Clicks != 900 || r.Total.Impressions != 28800 || r.Total.Position != 5.5 {
t.Errorf("totals: %+v", r)
}
if int(r.Anonymous+0.5) != 20 {
t.Errorf("anonymous share: %v", r.Anonymous)
}
if len(r.Pages) != 2 || r.Pages[0].Page != "https://whey.example/" || r.Pages[0].CTR() != 10 {
t.Errorf("pages: %+v", r.Pages)
}
if len(r.Unclicked) != 2 || r.Unclicked[0].Query != "whey price comparison" || r.Unclicked[0].Impressions != 18000 {
t.Errorf("unclicked: %+v", r.Unclicked)
}
if len(r.Protect) != 1 || !strings.Contains(r.Protect[0].Why, "100.0% of all clicks") {
t.Errorf("protect: %+v", r.Protect)
}
if len(r.Push) != 1 {
t.Fatalf("push: %+v", r.Push)
}
p := r.Push[0]
if p.Page != "https://whey.example/bulking/" || p.MainQuery != "whey price comparison" || int(p.MainShare+0.5) != 91 ||
!strings.Contains(p.Why, "Shown 19,800 times at position 7.6, 0 clicks. 91% of its impressions come from “whey price comparison”, where it's at 7.6.") {
t.Errorf("push: %+v", p)
}
}
+175
View File
@@ -0,0 +1,175 @@
// Package seo runs the weekly SEO loop for the company's websites, from
// Google Search Console's own numbers: what already ranks, the morning
// check, the Monday report, the audit, and the changes the user approves.
// Every number is computed here, from the data; the AI only writes words
// around them.
package seo
import (
"context"
"fmt"
"time"
"supermarket/internal/api/gsc"
"supermarket/internal/db"
)
const dayFormat = "2006-01-02"
// historyDays is how far back the first sync reads: Search Console keeps
// about 16 months.
const historyDays = 480
// refetchDays are read again on every sync: the last days' data can still
// change before it's final.
const refetchDays = 4
// chunkDays is how many days one set of requests covers.
const chunkDays = 30
func throughKey(site string) string { return "seo:gsc-through:" + site }
// SyncResult is what a sync read.
type SyncResult struct {
Site string `json:"site"`
At time.Time `json:"at"`
From string `json:"from"`
Through string `json:"through"` // the latest day with final data
Rows int `json:"rows"`
Error string `json:"error,omitempty"`
}
func lastKey(site string) string { return "seo:gsc-last:" + site }
// LastSync is a property's last sync, or nil.
func LastSync(d *db.DB, site string) (*SyncResult, error) {
var r SyncResult
ok, err := d.GetJSON(lastKey(site), &r)
if err != nil || !ok {
return nil, err
}
return &r, nil
}
// Through is the latest day stored for a property, or "".
func Through(d *db.DB, site string) string {
var t string
_, _ = d.GetJSON(throughKey(site), &t)
return t
}
// Sync reads a property's Search Console data, by day: the totals, each
// page, and each page and query. The first time it reads 16 months; after
// that, from a few days before the last final day.
func Sync(ctx context.Context, d *db.DB, c *gsc.Client, site string, now time.Time) (*SyncResult, error) {
res := &SyncResult{Site: site, At: now}
err := sync(ctx, d, c, site, now, res)
if err != nil {
res.Error = err.Error()
}
if perr := d.PutJSON(lastKey(site), res); perr != nil && err == nil {
err = perr
}
return res, err
}
func sync(ctx context.Context, d *db.DB, c *gsc.Client, site string, now time.Time, res *SyncResult) error {
today := now.UTC().Truncate(24 * time.Hour)
from := today.AddDate(0, 0, -historyDays)
if t := Through(d, site); t != "" {
if last, err := time.Parse(dayFormat, t); err == nil {
from = last.AddDate(0, 0, -refetchDays)
}
}
res.From = from.Format(dayFormat)
through := Through(d, site)
for start := from; !start.After(today); start = start.AddDate(0, 0, chunkDays) {
end := start.AddDate(0, 0, chunkDays-1)
if end.After(today) {
end = today
}
n, latest, err := syncRange(ctx, d, c, site, start.Format(dayFormat), end.Format(dayFormat))
if err != nil {
return err
}
res.Rows += n
if latest > through {
through = latest
}
}
res.Through = through
if through == "" {
return nil
}
return d.PutJSON(throughKey(site), through)
}
// syncRange replaces the stored days in [start, end] with Google's. It
// returns the rows stored and the latest day that had data.
func syncRange(ctx context.Context, d *db.DB, c *gsc.Client, site, start, end string) (int, string, error) {
q := func(dims ...string) ([]gsc.Row, error) {
return c.Analytics(ctx, site, gsc.Query{StartDate: start, EndDate: end, Dimensions: dims, Type: "web", DataState: "final"})
}
days, err := q("date")
if err != nil {
return 0, "", err
}
pages, err := q("date", "page")
if err != nil {
return 0, "", err
}
queries, err := q("date", "page", "query")
if err != nil {
return 0, "", err
}
tx, err := d.Begin()
if err != nil {
return 0, "", err
}
defer tx.Rollback()
for _, table := range []string{"gsc_site_days", "gsc_page_days", "gsc_query_days"} {
if _, err := tx.Exec(`DELETE FROM `+table+` WHERE site = ? AND date BETWEEN ? AND ?`, site, start, end); err != nil {
return 0, "", err
}
}
latest := ""
n := 0
for _, r := range days {
if len(r.Keys) < 1 {
continue
}
if r.Keys[0] > latest {
latest = r.Keys[0]
}
if _, err := tx.Exec(`INSERT INTO gsc_site_days VALUES (?, ?, ?, ?, ?)`,
site, r.Keys[0], int(r.Clicks), int(r.Impressions), r.Position*r.Impressions); err != nil {
return 0, "", err
}
n++
}
for _, r := range pages {
if len(r.Keys) < 2 {
continue
}
if _, err := tx.Exec(`INSERT INTO gsc_page_days VALUES (?, ?, ?, ?, ?, ?)`,
site, r.Keys[0], r.Keys[1], int(r.Clicks), int(r.Impressions), r.Position*r.Impressions); err != nil {
return 0, "", err
}
n++
}
for _, r := range queries {
if len(r.Keys) < 3 {
continue
}
if _, err := tx.Exec(`INSERT INTO gsc_query_days VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (site, date, page, query) DO NOTHING`,
site, r.Keys[0], r.Keys[1], r.Keys[2], int(r.Clicks), int(r.Impressions), r.Position*r.Impressions); err != nil {
return 0, "", err
}
n++
}
if err := tx.Commit(); err != nil {
return 0, "", fmt.Errorf("saving Search Console data: %w", err)
}
return n, latest, nil
}
+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
}
+103
View File
@@ -0,0 +1,103 @@
package web
import (
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"supermarket/internal/oauth"
"supermarket/internal/profile"
"supermarket/internal/secrets"
)
func TestSearchConsole(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/token":
r.ParseForm()
if r.PostForm.Get("client_secret") != "sec" || (r.PostForm.Get("code") != "c0de" && r.PostForm.Get("grant_type") != "refresh_token") {
w.WriteHeader(http.StatusBadRequest)
return
}
json.NewEncoder(w).Encode(map[string]any{"access_token": "tok", "refresh_token": "ref", "expires_in": 3600})
case r.URL.Path == "/userinfo":
json.NewEncoder(w).Encode(map[string]any{"email": "me@example.com"})
case r.URL.Path == "/sites":
json.NewEncoder(w).Encode(map[string]any{"siteEntry": []any{map[string]any{"siteUrl": "sc-domain:us.example", "permissionLevel": "siteOwner"}}})
case strings.HasSuffix(r.URL.Path, "/searchAnalytics/query"):
var q struct {
StartDate string `json:"startDate"`
Dimensions []string `json:"dimensions"`
}
json.NewDecoder(r.Body).Decode(&q)
var rows []any
if q.StartDate <= "2026-11-10" && q.StartDate >= "2026-10-20" {
day := "2026-11-10"
switch strings.Join(q.Dimensions, ",") {
case "date":
rows = append(rows, map[string]any{"keys": []string{day}, "clicks": 63, "impressions": 4200, "position": 9})
case "date,page":
rows = append(rows, map[string]any{"keys": []string{day, "https://us.example/pricing/"}, "clicks": 0, "impressions": 4000, "position": 6.5},
map[string]any{"keys": []string{day, "https://us.example/"}, "clicks": 63, "impressions": 200, "position": 1.2})
case "date,page,query":
rows = append(rows, map[string]any{"keys": []string{day, "https://us.example/pricing/", "nextcloud hosting price"}, "clicks": 0, "impressions": 3000, "position": 6})
}
}
json.NewEncoder(w).Encode(map[string]any{"rows": rows})
}
}))
defer srv.Close()
oauth.SetGoogleURLs(srv.URL+"/auth", srv.URL+"/token", srv.URL+"/userinfo")
gscBase = srv.URL
defer func() {
oauth.SetGoogleURLs("https://accounts.google.com/o/oauth2/v2/auth", "https://oauth2.googleapis.com/token", "https://openidconnect.googleapis.com/v1/userinfo")
gscBase = ""
gauth.token = ""
}()
s, h := newTestServer(t, nil)
profile.Save(s.DB, &profile.Profile{Name: "Us", Websites: []profile.Website{{URL: "https://us.example"}}})
if body := do(h, http.MethodGet, "/seo", nil, nil).Body.String(); !strings.Contains(body, "Connect Google Search Console") {
t.Error("the SEO page doesn't say to connect")
}
postForm(h, "/settings/search", url.Values{secrets.GoogleClientID: {"cid"}, secrets.GoogleClientSecret: {"sec"}})
body := do(h, http.MethodGet, "/settings/search", nil, nil).Body.String()
if !strings.Contains(body, "/auth/google/callback") || !strings.Contains(body, "Connect Search Console") {
t.Fatal("no redirect URI or Connect button")
}
rec := postForm(h, "/auth/google/start", nil)
loc, _ := url.Parse(rec.Header().Get("Location"))
q := loc.Query()
if !strings.HasPrefix(loc.String(), srv.URL+"/auth") || q.Get("access_type") != "offline" || !strings.Contains(q.Get("scope"), "webmasters.readonly") || q.Get("code_challenge") == "" {
t.Fatalf("start: %s", loc)
}
rec = do(h, http.MethodGet, "/auth/google/callback?state="+url.QueryEscape(q.Get("state"))+"&code=c0de", nil, nil)
if rec.Code != http.StatusSeeOther || !strings.HasPrefix(rec.Header().Get("Location"), "/settings/search?msg=google-connected") {
t.Fatalf("callback: %d %s %s", rec.Code, rec.Header().Get("Location"), rec.Body)
}
if s.Secrets.Get(secrets.GoogleRefreshToken) != "ref" {
t.Error("the refresh token wasn't saved")
}
body = do(h, http.MethodGet, "/settings/search", nil, nil).Body.String()
if !strings.Contains(body, "Connected as me@example.com") || !strings.Contains(body, `<option value="sc-domain:us.example"`) {
t.Fatalf("connected page: %s", body)
}
postForm(h, "/settings/search", url.Values{"property": {"sc-domain:us.example"}})
if p, _ := profile.Load(s.DB); p.Websites[0].SearchConsoleProperty != "sc-domain:us.example" {
t.Errorf("property: %+v", p.Websites)
}
if rec := postForm(h, "/settings/search/sync", url.Values{"back": {"/seo?site=0"}}); rec.Code != http.StatusSeeOther {
t.Fatalf("sync: %d %s", rec.Code, rec.Body)
}
body = do(h, http.MethodGet, "/seo", nil, nil).Body.String()
for _, want := range []string{"4,200", "/pricing/", "Shown 4,000 times at position 6.5, 0 clicks. 75% of its impressions come from “nextcloud hosting price”",
"nextcloud hosting price", "100.0% of the clicks come from searches Google doesn't name"} {
if !strings.Contains(body, want) {
t.Errorf("SEO page lacks %q", want)
}
}
}
+11 -1
View File
@@ -23,6 +23,7 @@ import (
"supermarket/internal/oauth"
"supermarket/internal/prospects"
"supermarket/internal/secrets"
"supermarket/internal/seo"
"supermarket/internal/signals"
)
@@ -158,6 +159,10 @@ func (s *Server) Handler() (http.Handler, error) {
mux.HandleFunc("POST /settings/email", s.emailSave)
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 /settings/search", s.searchSettingsPage)
mux.HandleFunc("POST /settings/search", s.searchSettingsSave)
mux.HandleFunc("POST /settings/search/sync", s.seoSync)
mux.HandleFunc("GET /settings/tracking", s.trackingPage)
mux.HandleFunc("POST /settings/tracking", s.trackingSave)
mux.HandleFunc("POST /settings/tracking/test/{source}", s.trackingTest)
@@ -277,6 +282,9 @@ func (s *Server) loadTemplates() error {
"xreserve": twitter.URLReserve,
// money shows cents as dollars: $1,234 or $12.50.
"money": money,
"num": seo.Thousands,
"dec1": func(f float64) string { return strconv.FormatFloat(f, 'f', 1, 64) },
"pagePath": pagePath,
"stage": signals.StageLabel,
"channel": signals.ChannelLabel,
"truncate": func(n int, s string) string {
@@ -347,7 +355,7 @@ type module struct {
var modules = []module{
{"content", "Content", "Phase 1", "Draft posts from partner and competitor news and your own products; review and publish to X, LinkedIn and Reddit.", "/content"},
{"prospects", "Prospects", "Phase 2", "Test buying signals through the whole funnel, from finding prospects to payment; add the people you approve to EspoCRM through Hermes.", "/signals"},
{"seo", "SEO", "Phase 3", "Audit your websites and open fixes as pull requests on your Hugo repositories.", ""},
{"seo", "SEO", "Phase 3", "Run the weekly SEO loop from Search Console: what ranks, what moved, and the changes waiting for your yes, opened as pull requests on your Hugo repositories.", "/seo"},
{"metrics", "Metrics", "Phase 4", "Pipeline influence, CAC, CLV and NRR from Stripe, EspoCRM and Plausible.", ""},
{"sites", "Sites", "Phase 5", "Build pages and sites from a component library and publish them through Gitea.", ""},
}
@@ -395,6 +403,8 @@ var flashes = map[string]string{
"deleted": "Deleted.",
"x-connected": "X is connected.",
"li-connected": "LinkedIn is connected.",
"google-connected": "Search Console is connected. Choose each website's property below, then sync.",
"synced": "Synced from Search Console.",
"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.",
+1 -1
View File
@@ -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",
"/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",
"/signals", "/signals?period=30d&channel=email", "/signals/new", "/settings/sources"} {
rec := do(h, http.MethodGet, path, nil, nil)
if rec.Code != http.StatusOK {
+37 -3
View File
@@ -358,6 +358,13 @@ func (s *Server) oauthStart(w http.ResponseWriter, r *http.Request) {
return
}
authURL, p, err = oauth.RedditStart(id, s.callbackURL("reddit"))
case "google":
id := s.Secrets.Get(secrets.GoogleClientID)
if id == "" || !s.Secrets.Has(secrets.GoogleClientSecret) {
http.Error(w, "Save Google's client ID and secret first.", http.StatusBadRequest)
return
}
authURL, p, err = oauth.GoogleStart(id, s.callbackURL("google"))
default:
http.NotFound(w, r)
return
@@ -386,15 +393,19 @@ func (s *Server) oauthCallback(w http.ResponseWriter, r *http.Request) {
p := s.pending[q.Get("state")]
delete(s.pending, q.Get("state")) // a state is good for one callback
s.mu.Unlock()
back, nav := "/settings/accounts", "settings/accounts"
if provider == "google" {
back, nav = "/settings/search", "settings/search"
}
if p == nil || p.Provider != provider || time.Since(p.Started) > oauthTTL {
s.Log.Warn("oauth: callback with an unknown or expired state", "provider", provider)
redirect(w, r, "/settings/accounts", "oauth-expired")
redirect(w, r, back, "oauth-expired")
return
}
fail := func(msg string) {
s.Log.Warn("oauth: sign-in failed", "provider", provider, "reason", msg)
s.render(w, r, "message", page{Title: "Sign-in failed", Nav: "settings/accounts", Error: msg,
Data: map[string]string{"Back": "/settings/accounts"}})
s.render(w, r, "message", page{Title: "Sign-in failed", Nav: nav, Error: msg,
Data: map[string]string{"Back": back}})
}
if e := q.Get("error"); e != "" {
// Some providers (LinkedIn) send the description HTML-escaped;
@@ -411,6 +422,29 @@ func (s *Server) oauthCallback(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
switch provider {
case "google":
res, err := oauth.GoogleExchange(ctx, s.Secrets.Get(secrets.GoogleClientID), s.Secrets.Get(secrets.GoogleClientSecret), code, p)
if err != nil {
fail(err.Error())
return
}
if res.RefreshToken == "" {
fail("Google sent no refresh token, so Supermarket couldn't read Search Console on its own. Remove Supermarket's access in your Google account's security settings, then connect again.")
return
}
email, err := oauth.GoogleEmail(ctx, res.AccessToken)
if err != nil {
s.Log.Warn("google: couldn't read the account's email", "err", err)
}
if err := s.Secrets.Set(map[string]string{secrets.GoogleRefreshToken: res.RefreshToken}); err != nil {
fail("Signed in, but couldn't save the token: " + err.Error())
return
}
s.setGoogleToken(res)
if err := s.saveConnection("google", Connection{Account: email, At: time.Now()}); err != nil {
s.Log.Error("saving connection", "err", err)
}
redirect(w, r, "/settings/search", "google-connected")
case "x":
res, err := oauth.XExchange(ctx, s.Secrets.Get(secrets.XClientID), s.Secrets.Get(secrets.XClientSecret), code, p)
if err != nil {
+6
View File
@@ -38,6 +38,11 @@
<a href="/content/published" {{if eq $nav "content/published"}}aria-current="page"{{end}}>Published</a>
</div>
{{end}}
{{if eq .ID "seo"}}
<div class="subnav">
<a href="/seo" {{if eq $nav "seo/ranks"}}aria-current="page"{{end}}>What ranks</a>
</div>
{{end}}
{{if eq .ID "prospects"}}
<div class="subnav">
<a href="/signals" {{if eq $nav "prospects/signals"}}aria-current="page"{{end}}>Signals</a>
@@ -95,6 +100,7 @@
<a href="/settings/sources" {{if eq .Nav "settings/sources"}}aria-current="page"{{end}}>{{template "icon" "prospects"}}Lead sources</a>
<a href="/settings/email" {{if eq .Nav "settings/email"}}aria-current="page"{{end}}>{{template "icon" "email"}}Email</a>
<a href="/settings/tracking" {{if eq .Nav "settings/tracking"}}aria-current="page"{{end}}>{{template "icon" "metrics"}}Website &amp; sales</a>
<a href="/settings/search" {{if eq .Nav "settings/search"}}aria-current="page"{{end}}>{{template "icon" "seo"}}Search engines</a>
<div class="nav-label">AI</div>
<a href="/settings/ai" {{if eq .Nav "settings/ai"}}aria-current="page"{{end}}>{{template "icon" "ai"}}AI</a>
</nav>
@@ -0,0 +1,47 @@
{{define "content"}}{{template "settings-start" .}}{{with .Data}}{{$d := .}}
<h2>Search engines</h2>
<p class="lede">Google Search Console is where Google says what it really shows for your sites: every number in SEO comes from it. Supermarket reads it (read-only) twice a day and keeps 16 months of it.</p>
<form method="post" action="/settings/search" autocomplete="off">
<section class="card" id="google">
<h3>Google Search Console</h3>
{{range .Fields}}{{template "key-field" (dict "F" . "Set" (index $d.Set .Name))}}{{end}}
<p class="help">Redirect URI to register on the OAuth client: <code id="google-redirect">{{.Redirect}}</code> <button type="button" class="link small" data-copy="google-redirect">Copy</button></p>
{{if .Connected}}
<p class="ok">Connected{{with .Account}} as {{.}}{{end}}.</p>
<label class="check small"><input type="checkbox" name="remove:google.refresh_token"> disconnect</label>
{{end}}
</section>
{{if .Connected}}
<section class="card">
<h3>Your websites' properties</h3>
{{with .PropsError}}<p class="error">Couldn't list your properties: {{.}}</p>{{end}}
{{if .Sites}}
{{range .Sites}}
<label>{{.URL}}
<select name="property">
<option value="">none</option>
{{$cur := .Property}}{{range $d.Properties}}<option value="{{.URL}}" {{if eq .URL $cur}}selected{{end}}>{{.URL}}</option>{{end}}
{{if and $cur (not $d.Properties)}}<option value="{{$cur}}" selected>{{$cur}}</option>{{end}}
</select>
{{with .Last}}<span class="help {{if .Error}}error-text{{end}}">Synced {{ago .At}}{{if .Error}}: {{.Error}}{{else}}; data through {{.Through}}{{end}}.</span>{{end}}
</label>
{{end}}
{{else}}<p class="help">Add your websites to the <a href="/settings/profile">profile</a> first.</p>{{end}}
{{if not .Properties}}<p class="help">This account sees no verified properties. Add your site in Search Console, or sign in with the account that owns it.</p>{{end}}
</section>
{{end}}
<div class="actions">
<button type="submit">Save</button>
</div>
</form>
<div class="actions">
{{if and (index .Set "google.client_id") (index .Set "google.client_secret")}}
<form method="post" action="/auth/google/start"><button type="submit" class="{{if .Connected}}secondary{{end}}">{{if .Connected}}Connect again{{else}}Connect Search Console{{end}}</button></form>
{{end}}
{{if .Connected}}<form method="post" action="/settings/search/sync" data-busy="Syncing…"><button type="submit" class="secondary">Sync now</button></form>{{end}}
</div>
{{end}}{{template "settings-end"}}{{end}}
+62
View File
@@ -0,0 +1,62 @@
{{define "content"}}{{with .Data}}{{$d := .}}
<div class="heading">
<h1>What already ranks</h1>
{{if .Current}}<div class="buttons">
<form method="post" action="/settings/search/sync" data-busy="Syncing…"><input type="hidden" name="back" value="/seo?site={{.Current.Index}}"><button type="submit" class="secondary">Sync now</button></form>
</div>{{end}}
</div>
<p class="lede">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.</p>
{{if not .Connected}}
<section class="card empty"><p>Connect Google Search Console under <a href="/settings/search">Settings → Search engines</a> first.</p></section>
{{else if not .Sites}}
<section class="card empty"><p>Choose the Search Console property for your website under <a href="/settings/search">Settings → Search engines</a>.</p></section>
{{else}}
{{if gt (len .Sites) 1}}<nav class="tabs">{{range .Sites}}<a href="/seo?site={{.Index}}" {{if eq .Index $d.Current.Index}}aria-current="page"{{end}}>{{.URL}}</a>{{end}}</nav>{{end}}
{{with .Ranks}}
<section class="card">
<p class="small muted">{{.Site}} · {{.From}} to {{.To}} (Search Console's final data is 2 to 3 days behind).</p>
<div class="funnel">
<div class="step"><span class="label">Clicks</span><strong>{{num .Total.Clicks}}</strong></div>
<div class="step"><span class="label">Impressions</span><strong>{{num .Total.Impressions}}</strong></div>
<div class="step"><span class="label">Click rate</span><strong>{{dec1 .Total.CTR}}%</strong></div>
<div class="step"><span class="label">Average position</span><strong>{{dec1 .Total.Position}}</strong></div>
</div>
{{if ge .Anonymous 0.0}}<p class="small">{{dec1 .Anonymous}}% of the clicks come from searches Google doesn't name, so the query tables below read low; the page tables don't.</p>{{end}}
</section>
<div class="grid">
<section class="card">
<h2>Protect</h2>
<p class="help">They carry the clicks: don't rewrite them for fun, don't change their address, look at them first.</p>
{{range .Protect}}<p><a href="{{.Page}}" target="_blank" rel="noopener noreferrer">{{pagePath .Page}}</a><br><span class="small">{{.Why}}</span></p>{{else}}<p class="help">No page has clicks yet.</p>{{end}}
</section>
<section class="card">
<h2>Push</h2>
<p class="help">On page one, shown a lot, hardly clicked: Google did the hard part, and the page loses at the click. Compare its main query with its title first.</p>
{{range .Push}}<p><a href="{{.Page}}" target="_blank" rel="noopener noreferrer">{{pagePath .Page}}</a><br><span class="small">{{.Why}}</span></p>{{else}}<p class="help">No page sits on page one with few clicks. Good, or too little data.</p>{{end}}
</section>
</div>
<h2>Best pages</h2>
{{if .Pages}}
<table class="list">
<thead><tr><th>Page</th><th class="num">Clicks</th><th class="num">Impressions</th><th class="num">Click rate</th><th class="num">Position</th></tr></thead>
<tbody>{{range .Pages}}<tr><td><a href="{{.Page}}" target="_blank" rel="noopener noreferrer">{{pagePath .Page}}</a></td><td class="num">{{num .Clicks}}</td><td class="num">{{num .Impressions}}</td><td class="num">{{dec1 .CTR}}%</td><td class="num">{{dec1 .Position}}</td></tr>{{end}}</tbody>
</table>
{{else}}<p class="help">No pages with data yet.</p>{{end}}
<h2>Shown a lot, hardly clicked</h2>
<p class="help">The searches Google shows you for most, with a click rate under 1%.</p>
{{if .Unclicked}}
<table class="list">
<thead><tr><th>Query</th><th class="num">Impressions</th><th class="num">Clicks</th><th class="num">Position</th></tr></thead>
<tbody>{{range .Unclicked}}<tr><td>{{.Query}}</td><td class="num">{{num .Impressions}}</td><td class="num">{{num .Clicks}}</td><td class="num">{{dec1 .Position}}</td></tr>{{end}}</tbody>
</table>
{{else}}<p class="help">None.</p>{{end}}
{{else}}
<section class="card empty"><p>No data yet for {{.Current.Property}}. {{with .Current.Last}}{{if .Error}}The last sync failed: {{.Error}}{{else}}Synced {{ago .At}}, with nothing back.{{end}}{{else}}Sync now to read it.{{end}}</p></section>
{{end}}
{{end}}
{{end}}{{end}}