Phase 8 part 1: links that bring visitors
The daily Plausible import also reads the visitors by referring site, linking page and entry page, with their sign-ups and leads (a new referrer_days table). Search engines, social networks, AI assistants, email and mail filters, work apps, the company's own sites and tagged links are told apart from links on other sites. SEO → Links lists the sites that sent visitors in 90 days, the pages they landed on and the sign-ups they brought, new ones first. A linking page Plausible names in full is kept as a known backlink (a new backlinks table, for parts 2 and 3); browsers mostly send only the site, so most aren't. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -625,6 +625,35 @@ CREATE TABLE page_days (
|
|||||||
leads INTEGER NOT NULL DEFAULT 0, -- visitors who sent a form (the Lead goal)
|
leads INTEGER NOT NULL DEFAULT 0, -- visitors who sent a form (the Lead goal)
|
||||||
PRIMARY KEY (site, date, page)
|
PRIMARY KEY (site, date, page)
|
||||||
);
|
);
|
||||||
|
`,
|
||||||
|
// 27: backlinks: who sends visitors (Plausible), the links found
|
||||||
|
// (Plausible, Bing, by hand), and whether each is still there.
|
||||||
|
`
|
||||||
|
CREATE TABLE referrer_days (
|
||||||
|
site TEXT NOT NULL, -- the Plausible site
|
||||||
|
date TEXT NOT NULL, -- YYYY-MM-DD
|
||||||
|
source TEXT NOT NULL, -- the referring site, as Plausible names it
|
||||||
|
referrer TEXT NOT NULL DEFAULT '', -- the linking page, when Plausible has it
|
||||||
|
page TEXT NOT NULL, -- the entry page's path
|
||||||
|
visitors INTEGER NOT NULL DEFAULT 0,
|
||||||
|
signups INTEGER NOT NULL DEFAULT 0,
|
||||||
|
leads INTEGER NOT NULL DEFAULT 0,
|
||||||
|
PRIMARY KEY (site, date, source, referrer, page)
|
||||||
|
);
|
||||||
|
CREATE TABLE backlinks (
|
||||||
|
id INTEGER PRIMARY KEY,
|
||||||
|
site TEXT NOT NULL, -- the website's URL, from the profile
|
||||||
|
source_url TEXT NOT NULL, -- the page that links
|
||||||
|
target TEXT NOT NULL DEFAULT '', -- our page it links to (a path), when known
|
||||||
|
anchor TEXT NOT NULL DEFAULT '',
|
||||||
|
origin TEXT NOT NULL, -- plausible, bing, manual
|
||||||
|
first_seen TEXT NOT NULL,
|
||||||
|
last_seen TEXT NOT NULL,
|
||||||
|
status TEXT NOT NULL DEFAULT 'unchecked', -- unchecked, kept, gone, page-gone, target-404
|
||||||
|
checked_at TEXT,
|
||||||
|
note TEXT NOT NULL DEFAULT '',
|
||||||
|
UNIQUE (site, source_url, target)
|
||||||
|
);
|
||||||
`,
|
`,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+26
-17
@@ -173,23 +173,9 @@ func ImportPages(ctx context.Context, d *db.DB, c *plausible.Client, sites []str
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return save(d, "pages", res, fmt.Errorf("%s: %w", site, err))
|
return save(d, "pages", res, fmt.Errorf("%s: %w", site, err))
|
||||||
}
|
}
|
||||||
var signups []plausible.Row
|
signups, err := signupRows(ctx, c, set, plausible.Query{SiteID: site, Metrics: []string{"visitors"}, DateRange: span, Dimensions: dims})
|
||||||
if len(set.Patterns) > 0 {
|
if err != nil {
|
||||||
var pats []any
|
return save(d, "pages", res, fmt.Errorf("%s: sign-ups: %w", site, err))
|
||||||
for _, p := range set.Patterns {
|
|
||||||
pats = append(pats, p)
|
|
||||||
}
|
|
||||||
signups, err = runAll(ctx, c, plausible.Query{SiteID: site, Metrics: []string{"visitors"}, DateRange: span, Dimensions: dims,
|
|
||||||
Filters: [][]any{{"is", "event:goal", []any{OutboundGoal}}, {"contains", "event:props:url", pats, map[string]any{"case_sensitive": false}}}})
|
|
||||||
if err != nil {
|
|
||||||
// Older Plausibles lack the case_sensitive modifier; patterns
|
|
||||||
// are stored in lower case, as links usually are.
|
|
||||||
signups, err = runAll(ctx, c, plausible.Query{SiteID: site, Metrics: []string{"visitors"}, DateRange: span, Dimensions: dims,
|
|
||||||
Filters: [][]any{{"is", "event:goal", []any{OutboundGoal}}, {"contains", "event:props:url", pats}}})
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
return save(d, "pages", res, fmt.Errorf("%s: sign-ups: %w", site, err))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
leads, err := runAll(ctx, c, plausible.Query{SiteID: site, Metrics: []string{"visitors"}, DateRange: span, Dimensions: dims,
|
leads, err := runAll(ctx, c, plausible.Query{SiteID: site, Metrics: []string{"visitors"}, DateRange: span, Dimensions: dims,
|
||||||
Filters: [][]any{{"is", "event:goal", []any{LeadGoal}}}})
|
Filters: [][]any{{"is", "event:goal", []any{LeadGoal}}}})
|
||||||
@@ -239,6 +225,29 @@ func ImportPages(ctx context.Context, d *db.DB, c *plausible.Client, sites []str
|
|||||||
return save(d, "pages", res, nil)
|
return save(d, "pages", res, nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// signupRows runs q for the visitors who clicked a sign-up link (none
|
||||||
|
// without a definition).
|
||||||
|
func signupRows(ctx context.Context, c *plausible.Client, set SignupSettings, q plausible.Query) ([]plausible.Row, error) {
|
||||||
|
if len(set.Patterns) == 0 {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
var pats []any
|
||||||
|
for _, p := range set.Patterns {
|
||||||
|
pats = append(pats, p)
|
||||||
|
}
|
||||||
|
base := q.Filters
|
||||||
|
q.Filters = append(append([][]any{}, base...), []any{"is", "event:goal", []any{OutboundGoal}},
|
||||||
|
[]any{"contains", "event:props:url", pats, map[string]any{"case_sensitive": false}})
|
||||||
|
rows, err := runAll(ctx, c, q)
|
||||||
|
if err != nil {
|
||||||
|
// Older Plausibles lack the case_sensitive modifier; patterns are
|
||||||
|
// stored in lower case, as links usually are.
|
||||||
|
q.Filters = append(append([][]any{}, base...), []any{"is", "event:goal", []any{OutboundGoal}}, []any{"contains", "event:props:url", pats})
|
||||||
|
rows, err = runAll(ctx, c, q)
|
||||||
|
}
|
||||||
|
return rows, err
|
||||||
|
}
|
||||||
|
|
||||||
// runAll runs a query through every page of its results.
|
// runAll runs a query through every page of its results.
|
||||||
func runAll(ctx context.Context, c *plausible.Client, q plausible.Query) ([]plausible.Row, error) {
|
func runAll(ctx context.Context, c *plausible.Client, q plausible.Query) ([]plausible.Row, error) {
|
||||||
const size = 10000
|
const size = 10000
|
||||||
|
|||||||
@@ -0,0 +1,289 @@
|
|||||||
|
package tracking
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"fmt"
|
||||||
|
"net/url"
|
||||||
|
"regexp"
|
||||||
|
"slices"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"supermarket/internal/api/plausible"
|
||||||
|
"supermarket/internal/db"
|
||||||
|
"supermarket/internal/profile"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Referrers: the sites that send visitors, from Plausible. A link on
|
||||||
|
// another site that brings visitors is a backlink worth knowing about;
|
||||||
|
// search engines, social networks, email, AI assistants and the company's
|
||||||
|
// own tagged links are counted apart.
|
||||||
|
|
||||||
|
// Kinds of referrer.
|
||||||
|
const (
|
||||||
|
RefLink = "link" // a page on another site: a backlink
|
||||||
|
RefSearch = "search" // a search engine
|
||||||
|
RefSocial = "social" // a social network
|
||||||
|
RefAI = "ai" // an AI assistant
|
||||||
|
RefEmail = "email" // a mail app, a newsletter, or a mail filter's link rewriter
|
||||||
|
RefApp = "app" // a work app: a CRM, chat, documents
|
||||||
|
RefOwn = "own" // another of the company's sites, or a subdomain
|
||||||
|
RefTagged = "tagged" // a link tagged with UTM, without a referring site
|
||||||
|
)
|
||||||
|
|
||||||
|
var refKinds = []struct {
|
||||||
|
kind string
|
||||||
|
re *regexp.Regexp
|
||||||
|
}{
|
||||||
|
{RefSearch, regexp.MustCompile(`(?i)^(google|bing|duckduckgo|yahoo|ecosia|brave|yandex|baidu|qwant|startpage|kagi|naver|seznam|search|presearch|mojeek)\b|google\.|bing\.com|duckduckgo|search\.brave|yahoo\.`)},
|
||||||
|
{RefAI, regexp.MustCompile(`(?i)chatgpt|openai|perplexity|claude\.ai|^claude\b|gemini|copilot|you\.com|phind|deepseek|mistral|meta\.ai|grok`)},
|
||||||
|
{RefApp, regexp.MustCompile(`(?i)force\.com|salesforce|hubspot|zoho|pipedrive|notion\.so|notion\.site|slack|teams\.microsoft|matrix\.org|element\.io|discord|zoom\.us|docs\.google|drive\.google|sharepoint|office\.com|atlassian|trello|asana|monday\.com|clickup|basecamp`)},
|
||||||
|
{RefSocial, regexp.MustCompile(`(?i)^(t\.co|twitter|x|x\.com|facebook|fb|instagram|linkedin|lnkd\.in|reddit|youtube|tiktok|pinterest|mastodon|threads|bluesky|bsky|discord|telegram|whatsapp|slack|quora)\b|reddit\.com|facebook\.com|linkedin\.com|youtube\.com|lnkd\.in|bsky\.app|t\.me`)},
|
||||||
|
{RefEmail, regexp.MustCompile(`(?i)mail|newsletter|outlook|proton|fastmail|tuta|substack|edgepilot|safelinks|urldefense|mimecast|proofpoint|barracuda|messagelabs|trendmicro|sophos`)},
|
||||||
|
}
|
||||||
|
|
||||||
|
// RefKind says what kind of referrer a Plausible source (and its linking
|
||||||
|
// page, when known) is, for a website on ownDomain.
|
||||||
|
func RefKind(source, referrer, ownDomain string) string {
|
||||||
|
host := strings.ToLower(source)
|
||||||
|
if u, err := url.Parse(referrer); err == nil && u.Hostname() != "" {
|
||||||
|
host = strings.ToLower(u.Hostname())
|
||||||
|
}
|
||||||
|
host = strings.TrimPrefix(host, "www.")
|
||||||
|
if ownDomain != "" && (host == ownDomain || strings.HasSuffix(host, "."+ownDomain)) {
|
||||||
|
return RefOwn
|
||||||
|
}
|
||||||
|
for _, k := range refKinds {
|
||||||
|
if k.re.MatchString(source) || k.re.MatchString(host) {
|
||||||
|
return k.kind
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !strings.Contains(host, ".") {
|
||||||
|
return RefTagged // a utm_source name, not a site
|
||||||
|
}
|
||||||
|
return RefLink
|
||||||
|
}
|
||||||
|
|
||||||
|
func refStateKey(site string) string { return "tracking:referrers-through:" + site }
|
||||||
|
|
||||||
|
// ImportReferrers reads, for each website and each whole day since the
|
||||||
|
// last import, the visitors by referring site, linking page and entry
|
||||||
|
// page, with their sign-ups and leads; and records each linking page on
|
||||||
|
// another site as a known backlink.
|
||||||
|
func ImportReferrers(ctx context.Context, d *db.DB, c *plausible.Client, websites []profile.Website, now time.Time) (*Result, error) {
|
||||||
|
res := &Result{At: now}
|
||||||
|
set := LoadSignups(d, nil)
|
||||||
|
yesterday := now.Local().AddDate(0, 0, -1).Format(dayFormat)
|
||||||
|
links := 0
|
||||||
|
// Older versions took a site's name for a linking page.
|
||||||
|
if _, err := d.Exec(`DELETE FROM backlinks WHERE origin = 'plausible' AND source_url NOT LIKE 'http%'`); err != nil {
|
||||||
|
return save(d, "referrers", res, err)
|
||||||
|
}
|
||||||
|
seen := map[string]bool{}
|
||||||
|
for _, w := range websites {
|
||||||
|
site := SiteID(w)
|
||||||
|
if site == "" || seen[site] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen[site] = true
|
||||||
|
var through string
|
||||||
|
if _, err := d.GetJSON(refStateKey(site), &through); err != nil {
|
||||||
|
return save(d, "referrers", res, err)
|
||||||
|
}
|
||||||
|
from := now.Local().AddDate(0, 0, -pageDays).Format(dayFormat)
|
||||||
|
if through != "" {
|
||||||
|
t, _ := time.ParseInLocation(dayFormat, through, time.Local)
|
||||||
|
from = t.AddDate(0, 0, 1).Format(dayFormat)
|
||||||
|
}
|
||||||
|
if from > yesterday {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
q := plausible.Query{SiteID: site, Metrics: []string{"visitors"}, DateRange: []string{from, yesterday},
|
||||||
|
Dimensions: []string{"time:day", "visit:source", "visit:referrer", "visit:entry_page"},
|
||||||
|
Filters: [][]any{{"is_not", "visit:source", []any{"Direct / None"}}}}
|
||||||
|
visits, err := runAll(ctx, c, q)
|
||||||
|
if err != nil {
|
||||||
|
return save(d, "referrers", res, fmt.Errorf("%s: %w", site, err))
|
||||||
|
}
|
||||||
|
signups, err := signupRows(ctx, c, set, q)
|
||||||
|
if err != nil {
|
||||||
|
return save(d, "referrers", res, fmt.Errorf("%s: sign-ups: %w", site, err))
|
||||||
|
}
|
||||||
|
lq := q
|
||||||
|
lq.Filters = append(append([][]any{}, q.Filters...), []any{"is", "event:goal", []any{LeadGoal}})
|
||||||
|
leads, err := runAll(ctx, c, lq)
|
||||||
|
if err != nil {
|
||||||
|
leads = nil // no Lead goal yet
|
||||||
|
}
|
||||||
|
type key struct{ day, source, referrer, page string }
|
||||||
|
all := map[key]*[3]int{}
|
||||||
|
add := func(rows []plausible.Row, i int) {
|
||||||
|
for _, r := range rows {
|
||||||
|
if len(r.Dimensions) < 4 || len(r.Metrics) < 1 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
k := key{r.Dimensions[0][:min(len(r.Dimensions[0]), 10)], r.Dimensions[1], none(r.Dimensions[2]), normalPath(r.Dimensions[3])}
|
||||||
|
if all[k] == nil {
|
||||||
|
all[k] = &[3]int{}
|
||||||
|
}
|
||||||
|
all[k][i] += int(r.Metrics[0])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
add(visits, 0)
|
||||||
|
add(signups, 1)
|
||||||
|
add(leads, 2)
|
||||||
|
own := ownDomain(w.URL)
|
||||||
|
tx, err := d.Begin()
|
||||||
|
if err != nil {
|
||||||
|
return save(d, "referrers", res, err)
|
||||||
|
}
|
||||||
|
for k, n := range all {
|
||||||
|
if _, err := tx.Exec(`INSERT INTO referrer_days (site, date, source, referrer, page, visitors, signups, leads) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
ON CONFLICT (site, date, source, referrer, page) DO UPDATE SET visitors = excluded.visitors, signups = excluded.signups, leads = excluded.leads`,
|
||||||
|
site, k.day, k.source, k.referrer, k.page, n[0], n[1], n[2]); err != nil {
|
||||||
|
tx.Rollback()
|
||||||
|
return save(d, "referrers", res, err)
|
||||||
|
}
|
||||||
|
res.Added++
|
||||||
|
if linkingPage(k.referrer) && RefKind(k.source, k.referrer, own) == RefLink {
|
||||||
|
added, err := noteBacklink(tx, w.URL, k.referrer, k.page, k.day)
|
||||||
|
if err != nil {
|
||||||
|
tx.Rollback()
|
||||||
|
return save(d, "referrers", res, err)
|
||||||
|
}
|
||||||
|
if added {
|
||||||
|
links++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := tx.Commit(); err != nil {
|
||||||
|
return save(d, "referrers", res, err)
|
||||||
|
}
|
||||||
|
if err := d.PutJSON(refStateKey(site), yesterday); err != nil {
|
||||||
|
return save(d, "referrers", res, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
res.Through = yesterday
|
||||||
|
res.Detail = fmt.Sprintf("Referring sites read; %d new linking %s found.", links, map[bool]string{true: "page", false: "pages"}[links == 1])
|
||||||
|
return save(d, "referrers", res, nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
// linkingPage says whether a referrer is a page's full address. Browsers
|
||||||
|
// usually send another site only their own address's origin, which says
|
||||||
|
// which site linked, not which page: that isn't a link to check.
|
||||||
|
func linkingPage(ref string) bool {
|
||||||
|
u, err := url.Parse(ref)
|
||||||
|
return err == nil && (u.Scheme == "http" || u.Scheme == "https") && u.Host != "" && strings.Trim(u.Path, "/") != ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// noteBacklink records a linking page that sent a visitor (when first and
|
||||||
|
// last seen), and says whether it's new.
|
||||||
|
func noteBacklink(tx *sql.Tx, site, source, target, day string) (bool, error) {
|
||||||
|
if u, err := url.Parse(source); err == nil {
|
||||||
|
u.Fragment = ""
|
||||||
|
source = u.String()
|
||||||
|
}
|
||||||
|
var n int
|
||||||
|
if err := tx.QueryRow(`SELECT count(*) FROM backlinks WHERE site = ? AND source_url = ? AND target = ?`, site, source, target).Scan(&n); err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
_, err := tx.Exec(`INSERT INTO backlinks (site, source_url, target, origin, first_seen, last_seen) VALUES (?, ?, ?, 'plausible', ?, ?)
|
||||||
|
ON CONFLICT (site, source_url, target) DO UPDATE SET
|
||||||
|
first_seen = min(first_seen, excluded.first_seen), last_seen = max(last_seen, excluded.last_seen)`,
|
||||||
|
site, source, target, day, day)
|
||||||
|
return n == 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func ownDomain(siteURL string) string {
|
||||||
|
if u, err := url.Parse(strings.TrimSpace(siteURL)); err == nil {
|
||||||
|
return strings.TrimPrefix(strings.ToLower(u.Hostname()), "www.")
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// Referrer is a referring site's numbers over a period.
|
||||||
|
type Referrer struct {
|
||||||
|
Source string
|
||||||
|
Kind string
|
||||||
|
Visitors int
|
||||||
|
Signups int // sign-ups and leads
|
||||||
|
Pages []string // the pages its visitors landed on, most first
|
||||||
|
Linking []string // its linking pages, when Plausible names them
|
||||||
|
FirstSeen string // the first day it sent anyone, in what's stored
|
||||||
|
New bool // first seen in the last 7 days of the period
|
||||||
|
}
|
||||||
|
|
||||||
|
// Referrers are a website's referring sites over the last days up to the
|
||||||
|
// last day read, most visitors first. ok is false before anything was read.
|
||||||
|
func Referrers(d *db.DB, w profile.Website, days int) (list []Referrer, ok bool, err error) {
|
||||||
|
site := SiteID(w)
|
||||||
|
var through string
|
||||||
|
if _, err := d.GetJSON(refStateKey(site), &through); err != nil || through == "" {
|
||||||
|
return nil, false, err
|
||||||
|
}
|
||||||
|
t, err := time.Parse(dayFormat, through)
|
||||||
|
if err != nil {
|
||||||
|
return nil, false, nil
|
||||||
|
}
|
||||||
|
from := t.AddDate(0, 0, -(days - 1)).Format(dayFormat)
|
||||||
|
weekAgo := t.AddDate(0, 0, -6).Format(dayFormat)
|
||||||
|
rows, err := d.Query(`SELECT source, referrer, page, sum(visitors), sum(signups) + sum(leads),
|
||||||
|
(SELECT min(date) FROM referrer_days r2 WHERE r2.site = r.site AND r2.source = r.source)
|
||||||
|
FROM referrer_days r WHERE site = ? AND date BETWEEN ? AND ? GROUP BY source, referrer, page`, site, from, through)
|
||||||
|
if err != nil {
|
||||||
|
return nil, false, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
own := ownDomain(w.URL)
|
||||||
|
by := map[string]*Referrer{}
|
||||||
|
pageVisits := map[string]map[string]int{}
|
||||||
|
for rows.Next() {
|
||||||
|
var source, referrer, page, first string
|
||||||
|
var v, conv int
|
||||||
|
if err := rows.Scan(&source, &referrer, &page, &v, &conv, &first); err != nil {
|
||||||
|
return nil, false, err
|
||||||
|
}
|
||||||
|
r := by[source]
|
||||||
|
if r == nil {
|
||||||
|
r = &Referrer{Source: source, Kind: RefKind(source, referrer, own), FirstSeen: first, New: first >= weekAgo}
|
||||||
|
by[source] = r
|
||||||
|
pageVisits[source] = map[string]int{}
|
||||||
|
}
|
||||||
|
r.Visitors += v
|
||||||
|
r.Signups += conv
|
||||||
|
pageVisits[source][page] += v
|
||||||
|
if linkingPage(referrer) && !slices.Contains(r.Linking, referrer) && len(r.Linking) < 5 {
|
||||||
|
r.Linking = append(r.Linking, referrer)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, false, err
|
||||||
|
}
|
||||||
|
for src, r := range by {
|
||||||
|
for p := range pageVisits[src] {
|
||||||
|
r.Pages = append(r.Pages, p)
|
||||||
|
}
|
||||||
|
pv := pageVisits[src]
|
||||||
|
slices.SortFunc(r.Pages, func(a, b string) int {
|
||||||
|
if pv[a] != pv[b] {
|
||||||
|
return pv[b] - pv[a]
|
||||||
|
}
|
||||||
|
return strings.Compare(a, b)
|
||||||
|
})
|
||||||
|
list = append(list, *r)
|
||||||
|
}
|
||||||
|
slices.SortFunc(list, func(a, b Referrer) int {
|
||||||
|
if a.New != b.New {
|
||||||
|
if a.New {
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
if a.Visitors != b.Visitors {
|
||||||
|
return b.Visitors - a.Visitors
|
||||||
|
}
|
||||||
|
return strings.Compare(a.Source, b.Source)
|
||||||
|
})
|
||||||
|
return list, true, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
package tracking
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"supermarket/internal/api/plausible"
|
||||||
|
"supermarket/internal/profile"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestRefKind(t *testing.T) {
|
||||||
|
for in, want := range map[[2]string]string{
|
||||||
|
{"Google", ""}: RefSearch,
|
||||||
|
{"t.co", ""}: RefSocial,
|
||||||
|
{"reddit.com", "https://www.reddit.com/r/selfhosted/x"}: RefSocial,
|
||||||
|
{"ChatGPT", ""}: RefAI,
|
||||||
|
{"perplexity.ai", ""}: RefAI,
|
||||||
|
{"wdtprs.com", "https://wdtprs.com/2026/11/post/"}: RefLink,
|
||||||
|
{"gitea.example.com", ""}: RefOwn,
|
||||||
|
{"linkedin", ""}: RefSocial,
|
||||||
|
{"newsletter", ""}: RefEmail,
|
||||||
|
{"partner-promo", ""}: RefTagged,
|
||||||
|
{"link.edgepilot.com", ""}: RefEmail,
|
||||||
|
{"rho.lightning.force.com", ""}: RefApp,
|
||||||
|
{"matrix.org", ""}: RefApp,
|
||||||
|
} {
|
||||||
|
if got := RefKind(in[0], in[1], "example.com"); got != want {
|
||||||
|
t.Errorf("%v: %s, want %s", in, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestImportReferrers(t *testing.T) {
|
||||||
|
d := openDB(t)
|
||||||
|
SaveSignups(d, []string{"/signup"})
|
||||||
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var q plausible.Query
|
||||||
|
json.NewDecoder(r.Body).Decode(&q)
|
||||||
|
goal := ""
|
||||||
|
for _, f := range q.Filters {
|
||||||
|
if f[1] == "event:goal" {
|
||||||
|
goal = fmt.Sprint(f[2])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rows := []plausible.Row{}
|
||||||
|
switch goal {
|
||||||
|
case "":
|
||||||
|
rows = []plausible.Row{
|
||||||
|
{Dimensions: []string{"2026-11-20", "wdtprs.com", "https://wdtprs.com/2026/11/post/#c", "/"}, Metrics: []float64{9}},
|
||||||
|
{Dimensions: []string{"2026-11-20", "tomwoods.com", "tomwoods.com", "/"}, Metrics: []float64{1}},
|
||||||
|
{Dimensions: []string{"2026-11-21", "Google", "", "/"}, Metrics: []float64{35}},
|
||||||
|
{Dimensions: []string{"2026-11-21", "selfhosted.blog", "https://selfhosted.blog/hosts/", "/headscale"}, Metrics: []float64{3}},
|
||||||
|
}
|
||||||
|
case "[" + OutboundGoal + "]":
|
||||||
|
rows = []plausible.Row{{Dimensions: []string{"2026-11-21", "selfhosted.blog", "https://selfhosted.blog/hosts/", "/headscale"}, Metrics: []float64{1}}}
|
||||||
|
}
|
||||||
|
json.NewEncoder(w).Encode(map[string]any{"results": rows})
|
||||||
|
}))
|
||||||
|
defer srv.Close()
|
||||||
|
c := plausible.New(srv.URL, "k")
|
||||||
|
w := profile.Website{URL: "https://example.com/"}
|
||||||
|
res, err := ImportReferrers(context.Background(), d, c, []profile.Website{w}, now)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if res.Detail != "Referring sites read; 2 new linking pages found." {
|
||||||
|
t.Errorf("detail: %s", res.Detail)
|
||||||
|
}
|
||||||
|
list, ok, err := Referrers(d, w, 90)
|
||||||
|
if err != nil || !ok || len(list) != 4 {
|
||||||
|
t.Fatalf("referrers: %+v %v %v", list, ok, err)
|
||||||
|
}
|
||||||
|
var blog *Referrer
|
||||||
|
for i := range list {
|
||||||
|
if list[i].Source == "selfhosted.blog" {
|
||||||
|
blog = &list[i]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if blog == nil || blog.Kind != RefLink || blog.Visitors != 3 || blog.Signups != 1 || blog.Pages[0] != "/headscale/" || !blog.New {
|
||||||
|
t.Errorf("blog: %+v", blog)
|
||||||
|
}
|
||||||
|
var n int
|
||||||
|
var src string
|
||||||
|
d.QueryRow(`SELECT count(*), min(source_url) FROM backlinks WHERE site = ?`, w.URL).Scan(&n, &src)
|
||||||
|
if n != 2 || src != "https://selfhosted.blog/hosts/" {
|
||||||
|
t.Errorf("backlinks: %d %s", n, src)
|
||||||
|
}
|
||||||
|
// Read again: nothing new, nothing doubled.
|
||||||
|
d.PutJSON(refStateKey("example.com"), "")
|
||||||
|
if res, _ := ImportReferrers(context.Background(), d, c, []profile.Website{w}, now); res.Detail != "Referring sites read; 0 new linking pages found." {
|
||||||
|
t.Errorf("again: %s", res.Detail)
|
||||||
|
}
|
||||||
|
if list, _, _ := Referrers(d, w, 90); list[len(list)-1].Visitors+list[0].Visitors < 12 {
|
||||||
|
t.Errorf("after again: %+v", list)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
package web
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"supermarket/internal/profile"
|
||||||
|
"supermarket/internal/tracking"
|
||||||
|
)
|
||||||
|
|
||||||
|
// SEO → Links: links from other sites to yours.
|
||||||
|
|
||||||
|
// linkDays is the period the Links page covers, as What ranks does.
|
||||||
|
const linkDays = 90
|
||||||
|
|
||||||
|
func (s *Server) seoLinksPage(w http.ResponseWriter, r *http.Request) {
|
||||||
|
data, cur := s.seoBase(r)
|
||||||
|
data["Path"] = "/seo/links"
|
||||||
|
data["Plausible"] = s.plausible() != nil
|
||||||
|
if cur != nil {
|
||||||
|
if p, _ := profile.Load(s.DB); p != nil {
|
||||||
|
for _, web := range p.Websites {
|
||||||
|
if web.URL != cur.URL {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
list, ok, err := tracking.Referrers(s.DB, web, linkDays)
|
||||||
|
if err != nil {
|
||||||
|
s.serverError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
data["Read"] = ok
|
||||||
|
var links []tracking.Referrer
|
||||||
|
others := map[string]int{}
|
||||||
|
for _, ref := range list {
|
||||||
|
if ref.Kind == tracking.RefLink {
|
||||||
|
links = append(links, ref)
|
||||||
|
} else {
|
||||||
|
others[ref.Kind] += ref.Visitors
|
||||||
|
}
|
||||||
|
}
|
||||||
|
data["Links"], data["Others"] = links, others
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var known int
|
||||||
|
_ = s.DB.QueryRow(`SELECT count(*) FROM backlinks WHERE site = ?`, cur.URL).Scan(&known)
|
||||||
|
data["Known"] = known
|
||||||
|
}
|
||||||
|
last, _ := tracking.Last(s.DB, "referrers")
|
||||||
|
data["Last"] = last
|
||||||
|
s.render(w, r, "seo-links", page{Title: "Links", Nav: "seo/links", Data: data})
|
||||||
|
}
|
||||||
@@ -223,6 +223,7 @@ func (s *Server) Handler() (http.Handler, error) {
|
|||||||
mux.HandleFunc("GET /seo/audit/status", s.seoAuditStatus)
|
mux.HandleFunc("GET /seo/audit/status", s.seoAuditStatus)
|
||||||
mux.HandleFunc("GET /seo/report", s.seoReportPage)
|
mux.HandleFunc("GET /seo/report", s.seoReportPage)
|
||||||
mux.HandleFunc("GET /seo/next", s.seoNextPage)
|
mux.HandleFunc("GET /seo/next", s.seoNextPage)
|
||||||
|
mux.HandleFunc("GET /seo/links", s.seoLinksPage)
|
||||||
mux.HandleFunc("GET /sites/pages/add", s.sitesAddPage)
|
mux.HandleFunc("GET /sites/pages/add", s.sitesAddPage)
|
||||||
mux.HandleFunc("POST /sites/pages/add", s.sitesAdd)
|
mux.HandleFunc("POST /sites/pages/add", s.sitesAdd)
|
||||||
mux.HandleFunc("POST /seo/next/dismiss", s.seoNextDismiss)
|
mux.HandleFunc("POST /seo/next/dismiss", s.seoNextDismiss)
|
||||||
|
|||||||
@@ -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",
|
"/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", "/content/1", "/content/1?dismissed=1", "/posts", "/posts?msg=drafted",
|
||||||
"/content/scheduled", "/content/published",
|
"/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", "/settings/search", "/seo", "/seo/check", "/seo/report", "/seo/next", "/seo/audit", "/seo/changes", "/seo/keywords", "/seo/briefs", "/seo/engines", "/metrics", "/metrics/customers", "/metrics/customers?show=all", "/metrics/spend", "/metrics/clv", "/metrics/clv?view=profit", "/metrics/publish", "/sites", "/sites?site=0", "/sites/previews", "/sites/pages", "/sites/publishing", "/sites/forms", "/sites/new", "/settings/backups",
|
"/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", "/seo/check", "/seo/report", "/seo/next", "/seo/links", "/seo/audit", "/seo/changes", "/seo/keywords", "/seo/briefs", "/seo/engines", "/metrics", "/metrics/customers", "/metrics/customers?show=all", "/metrics/spend", "/metrics/clv", "/metrics/clv?view=profit", "/metrics/publish", "/sites", "/sites?site=0", "/sites/previews", "/sites/pages", "/sites/publishing", "/sites/forms", "/sites/new", "/settings/backups",
|
||||||
"/signals", "/signals?period=30d&channel=email", "/signals/new", "/settings/sources"} {
|
"/signals", "/signals?period=30d&channel=email", "/signals/new", "/settings/sources"} {
|
||||||
rec := do(h, http.MethodGet, path, nil, nil)
|
rec := do(h, http.MethodGet, path, nil, nil)
|
||||||
if rec.Code != http.StatusOK {
|
if rec.Code != http.StatusOK {
|
||||||
|
|||||||
@@ -47,6 +47,7 @@
|
|||||||
<a href="/seo/report" {{if eq $nav "seo/report"}}aria-current="page"{{end}}>Monday report</a>
|
<a href="/seo/report" {{if eq $nav "seo/report"}}aria-current="page"{{end}}>Monday report</a>
|
||||||
<a href="/seo/next" {{if eq $nav "seo/next"}}aria-current="page"{{end}}>What to write next</a>
|
<a href="/seo/next" {{if eq $nav "seo/next"}}aria-current="page"{{end}}>What to write next</a>
|
||||||
<a href="/seo" {{if eq $nav "seo/ranks"}}aria-current="page"{{end}}>What ranks</a>
|
<a href="/seo" {{if eq $nav "seo/ranks"}}aria-current="page"{{end}}>What ranks</a>
|
||||||
|
<a href="/seo/links" {{if eq $nav "seo/links"}}aria-current="page"{{end}}>Links</a>
|
||||||
<a href="/seo/changes" {{if eq $nav "seo/changes"}}aria-current="page"{{end}}>Changes</a>
|
<a href="/seo/changes" {{if eq $nav "seo/changes"}}aria-current="page"{{end}}>Changes</a>
|
||||||
<a href="/seo/keywords" {{if eq $nav "seo/keywords"}}aria-current="page"{{end}}>Next keywords</a>
|
<a href="/seo/keywords" {{if eq $nav "seo/keywords"}}aria-current="page"{{end}}>Next keywords</a>
|
||||||
<a href="/seo/briefs" {{if eq $nav "seo/briefs"}}aria-current="page"{{end}}>Briefs and pages</a>
|
<a href="/seo/briefs" {{if eq $nav "seo/briefs"}}aria-current="page"{{end}}>Briefs and pages</a>
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
{{define "content"}}{{with .Data}}{{$d := .}}
|
||||||
|
<div class="heading"><h1>Links</h1></div>
|
||||||
|
<p class="lede">Links from other sites to yours: the ones that bring visitors and sign-ups, the ones search engines have found, and whether each is still there. A link that brings people who sign up is worth more than any number of links nobody clicks.</p>
|
||||||
|
|
||||||
|
{{template "seo-sites" .}}
|
||||||
|
{{if .Current}}
|
||||||
|
<section class="card">
|
||||||
|
<h2>Links that bring visitors</h2>
|
||||||
|
<p class="small">From Plausible, the last 90 days: other sites whose links people followed to yours, the pages they landed on, and how many of them signed up or sent a form. Search engines, social networks, email and AI assistants are counted apart, below.</p>
|
||||||
|
{{if not $d.Plausible}}<p class="warn-text small">Save a Plausible key under <a href="/settings/tracking">Settings → Website & sales</a> to see them.</p>
|
||||||
|
{{else if not $d.Read}}<p class="help">Not read yet: it's read with the daily Plausible import, or now with <em>Import now</em> under <a href="/settings/tracking">Settings → Website & sales</a>.</p>
|
||||||
|
{{else}}
|
||||||
|
{{with $d.Links}}
|
||||||
|
<table class="list">
|
||||||
|
<thead><tr><th>Site</th><th class="num">Visitors</th><th class="num">Sign-ups</th><th>Landed on</th><th>The linking page</th></tr></thead>
|
||||||
|
<tbody>{{range .}}<tr>
|
||||||
|
<td><strong>{{.Source}}</strong>{{if .New}} <span class="badge published">new</span>{{end}}<br><span class="small muted">since {{.FirstSeen}}</span></td>
|
||||||
|
<td class="num">{{num .Visitors}}</td>
|
||||||
|
<td class="num">{{if .Signups}}<strong>{{num .Signups}}</strong>{{else}}<span class="muted">0</span>{{end}}</td>
|
||||||
|
<td class="small">{{range $i, $p := .Pages}}{{if lt $i 3}}{{if $i}}, {{end}}{{$p}}{{end}}{{end}}</td>
|
||||||
|
<td class="small">{{range .Linking}}<a href="{{.}}" target="_blank" rel="noopener noreferrer">{{truncate 60 .}}</a><br>{{else}}<span class="muted">not given</span>{{end}}</td>
|
||||||
|
</tr>{{end}}</tbody>
|
||||||
|
</table>
|
||||||
|
{{else}}<p class="help">No other site sent visitors in the last 90 days.</p>{{end}}
|
||||||
|
{{with $d.Others}}<p class="small muted">Also, in visitors: {{with index . "search"}}search engines {{num .}} · {{end}}{{with index . "social"}}social networks {{num .}} · {{end}}{{with index . "ai"}}AI assistants {{num .}} · {{end}}{{with index . "email"}}email {{num .}} · {{end}}{{with index . "app"}}work apps (CRMs, chat, documents) {{num .}} · {{end}}{{with index . "own"}}your other sites {{num .}} · {{end}}{{with index . "tagged"}}tagged links {{num .}}{{end}}</p>{{end}}
|
||||||
|
<p class="small muted">Browsers usually tell a site only which site a visitor came from, not the page: where the page isn't given, find the link on that site, or add it by hand once that's possible. Visits with no referrer at all (typed in, bookmarks, apps that hide it) aren't counted here. {{with $d.Known}}{{.}} linking {{if eq . 1}}page is{{else}}pages are{{end}} known.{{end}}</p>
|
||||||
|
{{end}}
|
||||||
|
{{template "last-read" $d.Last}}
|
||||||
|
</section>
|
||||||
|
{{end}}
|
||||||
|
{{end}}{{end}}
|
||||||
|
|
||||||
|
{{define "last-read"}}{{with .}}<p class="small {{if .Error}}error-text{{else}}muted{{end}}">Last read {{ago .At}}: {{if .Error}}{{.Error}}{{else}}{{.Detail}}{{end}}</p>{{end}}{{end}}
|
||||||
@@ -230,6 +230,11 @@ func (s *Server) runTracking(ctx context.Context, source string) error {
|
|||||||
if _, perr := tracking.ImportPages(ctx, s.DB, c, s.sites(), now); perr != nil && err == nil {
|
if _, perr := tracking.ImportPages(ctx, s.DB, c, s.sites(), now); perr != nil && err == nil {
|
||||||
err = fmt.Errorf("pages: %w", perr)
|
err = fmt.Errorf("pages: %w", perr)
|
||||||
}
|
}
|
||||||
|
if p, _ := profile.Load(s.DB); p != nil {
|
||||||
|
if _, rerr := tracking.ImportReferrers(ctx, s.DB, c, p.Websites, now); rerr != nil && err == nil {
|
||||||
|
err = fmt.Errorf("referring sites: %w", rerr)
|
||||||
|
}
|
||||||
|
}
|
||||||
return err
|
return err
|
||||||
case tracking.SourceStripe:
|
case tracking.SourceStripe:
|
||||||
c := s.stripe()
|
c := s.stripe()
|
||||||
|
|||||||
Reference in New Issue
Block a user