Phase 7 part 1: sign-ups by page
Settings → Website & sales says which clicked links count as a sign-up: Supermarket suggests the sign-up, trial and checkout links visitors clicked, and the user ticks, unticks or adds their own. The Plausible import reads, per page a visit began on, the visitors, sign-ups and form leads (a new page_days table); What ranks, the audit and Sites show visits and sign-ups next to each page. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,335 @@
|
||||
package tracking
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/api/plausible"
|
||||
"supermarket/internal/db"
|
||||
)
|
||||
|
||||
// Pages: what each page of a website turns visits into. Plausible ties a
|
||||
// visit to the page it began on (its entry page), so a sign-up or a lead
|
||||
// counts for the page that brought the visitor, wherever on the site they
|
||||
// clicked or sent the form.
|
||||
|
||||
// OutboundGoal is Plausible's goal for clicks on links to other sites;
|
||||
// the link is its url property.
|
||||
const OutboundGoal = "Outbound Link: Click"
|
||||
|
||||
// SignupSettings say which outbound links are sign-ups. Until the user
|
||||
// saves them, the links Supermarket suggests count.
|
||||
type SignupSettings struct {
|
||||
Patterns []string `json:"patterns"` // a link counts if it contains one (any case)
|
||||
Saved bool `json:"saved"`
|
||||
}
|
||||
|
||||
const signupKey = "tracking:signups"
|
||||
|
||||
// LoadSignups is the saved definition, or the suggested one.
|
||||
func LoadSignups(d *db.DB, links []string) SignupSettings {
|
||||
var s SignupSettings
|
||||
if ok, _ := d.GetJSON(signupKey, &s); ok && s.Saved {
|
||||
return s
|
||||
}
|
||||
return SignupSettings{Patterns: SuggestSignups(links)}
|
||||
}
|
||||
|
||||
// SaveSignups stores the definition; the page numbers are read again with
|
||||
// it on the next import.
|
||||
func SaveSignups(d *db.DB, patterns []string) error {
|
||||
var clean []string
|
||||
for _, p := range patterns {
|
||||
p = strings.ToLower(strings.TrimSpace(p))
|
||||
if p != "" && !slices.Contains(clean, p) {
|
||||
clean = append(clean, p)
|
||||
}
|
||||
}
|
||||
if err := d.PutJSON(signupKey, SignupSettings{Patterns: clean, Saved: true}); err != nil {
|
||||
return err
|
||||
}
|
||||
return ResetPages(d)
|
||||
}
|
||||
|
||||
// signupLink spots links that start a sign-up: a signup, register or trial
|
||||
// page, or a checkout.
|
||||
var signupLink = regexp.MustCompile(`(?i)(sign-?up|register|registration|/join\b|free-?trial|start-?trial|checkout|/subscribe\b|/buy\b|/order\b)`)
|
||||
|
||||
// SuggestSignups picks, from links people clicked, the ones that look like
|
||||
// the start of a sign-up, as patterns (the link without its query).
|
||||
func SuggestSignups(links []string) []string {
|
||||
var out []string
|
||||
for _, l := range links {
|
||||
if !signupLink.MatchString(l) {
|
||||
continue
|
||||
}
|
||||
p := strings.ToLower(l)
|
||||
if u, err := url.Parse(l); err == nil && u.Host != "" {
|
||||
p = strings.ToLower(u.Host + strings.TrimRight(u.Path, "/"))
|
||||
}
|
||||
if !slices.Contains(out, p) {
|
||||
out = append(out, p)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// OutboundLink is a link people clicked, and how many visitors did.
|
||||
type OutboundLink struct {
|
||||
URL string
|
||||
Visitors int
|
||||
Signup bool // counts as a sign-up under the current definition
|
||||
}
|
||||
|
||||
// OutboundLinks are the links visitors clicked on a site in the last 30
|
||||
// days, most clicked first, so the user can say which are sign-ups.
|
||||
func OutboundLinks(ctx context.Context, c *plausible.Client, site string) ([]OutboundLink, error) {
|
||||
rows, err := c.Run(ctx, plausible.Query{SiteID: site, Metrics: []string{"visitors"}, DateRange: "30d",
|
||||
Dimensions: []string{"event:props:url"}, Filters: [][]any{{"is", "event:goal", []any{OutboundGoal}}},
|
||||
Pagination: &plausible.Pagination{Limit: 50}})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out []OutboundLink
|
||||
for _, r := range rows {
|
||||
if len(r.Dimensions) > 0 && len(r.Metrics) > 0 && r.Dimensions[0] != "" && r.Dimensions[0] != "(none)" {
|
||||
out = append(out, OutboundLink{URL: r.Dimensions[0], Visitors: int(r.Metrics[0])})
|
||||
}
|
||||
}
|
||||
slices.SortStableFunc(out, func(a, b OutboundLink) int { return b.Visitors - a.Visitors })
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Matches says whether a link is a sign-up under the definition.
|
||||
func (s SignupSettings) Matches(link string) bool {
|
||||
l := strings.ToLower(link)
|
||||
for _, p := range s.Patterns {
|
||||
if strings.Contains(l, p) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// pageDays is how far back the first page import reads.
|
||||
const pageDays = 400
|
||||
|
||||
func pagesStateKey(site string) string { return "tracking:pages-through:" + site }
|
||||
|
||||
// ResetPages forgets the page numbers, to read them again (after the
|
||||
// sign-up definition changed).
|
||||
func ResetPages(d *db.DB) error {
|
||||
if _, err := d.Exec(`DELETE FROM page_days`); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := d.Exec(`DELETE FROM settings WHERE key LIKE 'tracking:pages-through:%'`)
|
||||
return err
|
||||
}
|
||||
|
||||
// ImportPages reads, for each site and each whole day since the last
|
||||
// import, the visitors, sign-ups and form leads by entry page. Sign-ups
|
||||
// are visitors who clicked a link the definition counts; leads, visitors
|
||||
// who sent a form (the Lead goal, when it's set up in Plausible).
|
||||
func ImportPages(ctx context.Context, d *db.DB, c *plausible.Client, sites []string, now time.Time) (*Result, error) {
|
||||
res := &Result{At: now}
|
||||
set := LoadSignups(d, nil)
|
||||
if !set.Saved {
|
||||
// Not defined yet: suggest from the links people clicked.
|
||||
for _, site := range sites {
|
||||
links, err := OutboundLinks(ctx, c, site)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
var urls []string
|
||||
for _, l := range links {
|
||||
urls = append(urls, l.URL)
|
||||
}
|
||||
set.Patterns = append(set.Patterns, SuggestSignups(urls)...)
|
||||
}
|
||||
}
|
||||
yesterday := now.Local().AddDate(0, 0, -1).Format(dayFormat)
|
||||
days := 0
|
||||
for _, site := range sites {
|
||||
var through string
|
||||
if _, err := d.GetJSON(pagesStateKey(site), &through); err != nil {
|
||||
return save(d, "pages", 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
|
||||
}
|
||||
dims := []string{"time:day", "visit:entry_page"}
|
||||
span := []string{from, yesterday}
|
||||
visits, err := runAll(ctx, c, plausible.Query{SiteID: site, Metrics: []string{"visitors"}, DateRange: span, Dimensions: dims})
|
||||
if err != nil {
|
||||
return save(d, "pages", res, fmt.Errorf("%s: %w", site, err))
|
||||
}
|
||||
var signups []plausible.Row
|
||||
if len(set.Patterns) > 0 {
|
||||
var pats []any
|
||||
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,
|
||||
Filters: [][]any{{"is", "event:goal", []any{LeadGoal}}}})
|
||||
if err != nil {
|
||||
leads = nil // no Lead goal yet: no leads, not a failure
|
||||
}
|
||||
type key struct{ day, page string }
|
||||
all := map[key]*[3]int{}
|
||||
add := func(rows []plausible.Row, i int) {
|
||||
for _, r := range rows {
|
||||
if len(r.Dimensions) < 2 || len(r.Metrics) < 1 {
|
||||
continue
|
||||
}
|
||||
k := key{r.Dimensions[0][:min(len(r.Dimensions[0]), 10)], normalPath(r.Dimensions[1])}
|
||||
if all[k] == nil {
|
||||
all[k] = &[3]int{}
|
||||
}
|
||||
all[k][i] += int(r.Metrics[0])
|
||||
}
|
||||
}
|
||||
add(visits, 0)
|
||||
add(signups, 1)
|
||||
add(leads, 2)
|
||||
tx, err := d.Begin()
|
||||
if err != nil {
|
||||
return save(d, "pages", res, err)
|
||||
}
|
||||
for k, n := range all {
|
||||
if _, err := tx.Exec(`INSERT INTO page_days (site, date, page, visitors, signups, leads) VALUES (?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT (site, date, page) DO UPDATE SET visitors = excluded.visitors, signups = excluded.signups, leads = excluded.leads`,
|
||||
site, k.day, k.page, n[0], n[1], n[2]); err != nil {
|
||||
tx.Rollback()
|
||||
return save(d, "pages", res, err)
|
||||
}
|
||||
res.Added++
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return save(d, "pages", res, err)
|
||||
}
|
||||
if err := d.PutJSON(pagesStateKey(site), yesterday); err != nil {
|
||||
return save(d, "pages", res, err)
|
||||
}
|
||||
days++
|
||||
}
|
||||
res.Through = yesterday
|
||||
res.Detail = fmt.Sprintf("Pages read for %d %s.", days, map[bool]string{true: "site", false: "sites"}[days == 1])
|
||||
return save(d, "pages", res, nil)
|
||||
}
|
||||
|
||||
// runAll runs a query through every page of its results.
|
||||
func runAll(ctx context.Context, c *plausible.Client, q plausible.Query) ([]plausible.Row, error) {
|
||||
const size = 10000
|
||||
var out []plausible.Row
|
||||
for offset := 0; ; offset += size {
|
||||
q.Pagination = &plausible.Pagination{Limit: size, Offset: offset}
|
||||
rows, err := c.Run(ctx, q)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, rows...)
|
||||
if len(rows) < size || offset > 50*size {
|
||||
return out, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// normalPath is a page's path as the tables key it: lower case, with a
|
||||
// trailing slash, without a query or index.html.
|
||||
func normalPath(p string) string {
|
||||
if u, err := url.Parse(p); err == nil && u.Path != "" {
|
||||
p = u.Path
|
||||
}
|
||||
p = strings.ToLower(strings.TrimSuffix(p, "index.html"))
|
||||
if !strings.HasSuffix(p, "/") {
|
||||
p += "/"
|
||||
}
|
||||
if !strings.HasPrefix(p, "/") {
|
||||
p = "/" + p
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// PageNumbers are a page's visitors, sign-ups and leads over a period.
|
||||
type PageNumbers struct {
|
||||
Visitors int `json:"visitors"`
|
||||
Signups int `json:"signups"`
|
||||
Leads int `json:"leads"`
|
||||
}
|
||||
|
||||
// Conversions are the sign-ups and the leads together.
|
||||
func (p PageNumbers) Conversions() int { return p.Signups + p.Leads }
|
||||
|
||||
// Rate is conversions per visitor, 0 without visitors.
|
||||
func (p PageNumbers) Rate() float64 {
|
||||
if p.Visitors == 0 {
|
||||
return 0
|
||||
}
|
||||
return float64(p.Conversions()) / float64(p.Visitors)
|
||||
}
|
||||
|
||||
// Pages are a site's numbers by page (normalized path) over the last days
|
||||
// up to the last day read. ok is false before anything was read.
|
||||
func Pages(d *db.DB, site string, days int) (map[string]PageNumbers, bool, error) {
|
||||
var through string
|
||||
if _, err := d.GetJSON(pagesStateKey(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)
|
||||
rows, err := d.Query(`SELECT page, sum(visitors), sum(signups), sum(leads) FROM page_days
|
||||
WHERE site = ? AND date BETWEEN ? AND ? GROUP BY page`, site, from, through)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := map[string]PageNumbers{}
|
||||
for rows.Next() {
|
||||
var p string
|
||||
var n PageNumbers
|
||||
if err := rows.Scan(&p, &n.Visitors, &n.Signups, &n.Leads); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
out[p] = n
|
||||
}
|
||||
return out, true, rows.Err()
|
||||
}
|
||||
|
||||
// PathOf is the key Pages uses for a page's address.
|
||||
func PathOf(pageURL string) string { return normalPath(pageURL) }
|
||||
|
||||
// Total sums a site's pages.
|
||||
func Total(pages map[string]PageNumbers) PageNumbers {
|
||||
var t PageNumbers
|
||||
for _, p := range pages {
|
||||
t.Visitors += p.Visitors
|
||||
t.Signups += p.Signups
|
||||
t.Leads += p.Leads
|
||||
}
|
||||
return t
|
||||
}
|
||||
Reference in New Issue
Block a user