db.DB wraps database/sql for either database. The SQL stays SQLite's: on Postgres each statement's ? become $n and LIKE ignores case as SQLite's does, and the Postgres schema (postgres.sql, schema 29 as a whole) adds SQLite's instr, json_extract and two-argument max/min, and a nocase ICU collation. Needs Postgres 18. LastInsertId became db.Insert (RETURNING id), INSERT OR IGNORE became ON CONFLICT DO NOTHING, upserts qualify their columns, and three queries group by every column they use. SUPERMARKET_TEST_POSTGRES runs the test suite on Postgres, a new schema per test; all tests pass on both. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
289 lines
11 KiB
Go
289 lines
11 KiB
Go
package tracking
|
|
|
|
import (
|
|
"context"
|
|
"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 *db.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(backlinks.first_seen, excluded.first_seen), last_seen = max(backlinks.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 site, 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
|
|
}
|