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:
2026-11-24 07:07:47 -07:00
co-authored by Claude Opus 5.5
parent aeba28b658
commit e9871082b5
12 changed files with 733 additions and 26 deletions
+128 -14
View File
@@ -15,11 +15,43 @@ running a Federated Core can install as a CoreDesktop sibling.
| Core MCP / EspoCRM | Reached through the **local Hermes agent**, which gets an `mcp_servers` entry for the Core's MCP hub | | Core MCP / EspoCRM | Reached through the **local Hermes agent**, which gets an `mcp_servers` entry for the Core's MCP hub |
| Billing data | **Stripe** first, for CAC, CLV and NRR | | Billing data | **Stripe** first, for CAC, CLV and NRR |
| Existing content work | **Kept.** The hard-coded app list becomes the **Inventory** of partners and competitors | | Existing content work | **Kept.** The hard-coded app list becomes the **Inventory** of partners and competitors |
| Websites and components | The suite builds the company's **websites** from a reusable **component library** | | Websites and components | Pages are built from **each site's own section types** (decided 2026-11-22, Phase 5); **new sites** start from Supermarket's **shared theme**, copied into each site, with federated-website's look and the site's brand (Phase 6) |
| Publishing | Sites are pushed to a **Gitea repository**. The user sets up the hooks that publish it to the Hugo server | | Publishing | Sites are pushed to a **Gitea repository**. The user sets up the hooks that publish it to the Hugo server |
| Contact enrichment | Third-party services allowed, behind a pluggable interface (section 6) | | Contact enrichment | Third-party services allowed, behind a pluggable interface (section 6) |
| AI for the app | Uses Hermes' Anthropic key and model when the user agrees (2026-11-20), copied to `hermes-ai.json` by `supermarket hermes` and `update.sh`. It calls the model directly, never through Hermes: post writing reads untrusted web text, which must not reach an agent with tools and CRM access | | AI for the app | Uses Hermes' Anthropic key and model when the user agrees (2026-11-20), copied to `hermes-ai.json` by `supermarket hermes` and `update.sh`. It calls the model directly, never through Hermes: post writing reads untrusted web text, which must not reach an agent with tools and CRM access |
| Suite shape | One repo, one app with modules (Content, Prospects, SEO, Metrics, Sites), plus an MCP endpoint for agents | | Suite shape | One repo, one app with modules (Content, Prospects, SEO, Metrics, Sites), plus an MCP endpoint for agents |
| Backups | SQLite's own `VACUUM INTO`, on request, before every migration and daily, in `<data>/backups`; secrets never in them (Phase 6) |
## Where things stand (2026-11-22)
**Phases 0–6 are built and merged into `main`** (3ddf716; the user pushes
from their own terminal). Only Phase 1 is tagged (`v0.1.0`); whether to
tag the later phases is the user's call. Every module works: Content, Prospects, SEO,
Metrics and Sites, with Settings → Backups.
**Next: a run through TEST.md by hand** (planned for 2026-11-23), fixing
what it turns up. Make a backup first: `supermarket backup "before
testing"`.
**Waiting on the user, or on others:**
- *The CRM bridge*: the Core's MCP hub reaches EspoCRM at a stale address;
with the Core's developer. It holds up the CRM queue, the 385 customer
matches waiting for Accounts, and Phase 4 part 7 (pipeline influence).
- *Lead forms*: a Lead Capture in EspoCRM, the lead-forms pull request on
federated-website, and a `Lead` goal in Plausible.
- *The LinkedIn page*: LinkedIn approving the second app (Community
Management API).
- *A first new site*: an empty repository on Gitea, and its deploy hook.
- *Metrics*: the start month (2025-01 suggested), the per-product margins,
other spend; publishing the open metrics page is the user's choice.
- *SEO*: the search-engine setup pull request on federated-website (adds a
sitemap and robots.txt; Google still has an old www sitemap from 2023).
- *The shopping cart*: it must save the UTM tags in Stripe Checkout's
metadata for sign-ups to count per signal (and per landing-page variant).
- *Reddit*: API access needs Reddit's approval; until then, posts by hand.
- *Not yet tried with real money or data*: discovery (web searches),
building site pages with the AI, sending outreach email through the
Core's mail server.
## 2. Requirements from the notes ## 2. Requirements from the notes
@@ -300,7 +332,7 @@ What item 8 turned up:
the Core's developer: it isn't known yet whether the hub blocks them for the Core's developer: it isn't known yet whether the hub blocks them for
non-admins. non-admins.
Next: Phase 1, under way (see below). Phase 1 followed (see below).
Supermarket's half can be checked before the token arrives: ask Hermes the Supermarket's half can be checked before the token arrives: ask Hermes the
check-in question now. It should reach `bridge_checkin` and note that check-in question now. It should reach `bridge_checkin` and note that
@@ -326,9 +358,12 @@ mcphub failed.
`hermes.json`?~~ No. Answered 2026-11-19: it uses the MCP socket instead. `hermes.json`?~~ No. Answered 2026-11-19: it uses the MCP socket instead.
- ~~Does `hermes config set` write nested `mcp_servers.*.headers` keys - ~~Does `hermes config set` write nested `mcp_servers.*.headers` keys
correctly?~~ Yes. correctly?~~ Yes.
- What EspoCRM tools does the hub expose? - ~~What EspoCRM tools does the hub expose?~~ Six generic record tools
- Can Hermes cron jobs call MCP tools? (above). Answered 2026-11-20.
- How reliable is a run of 50 queued actions? - Can Hermes cron jobs call MCP tools? Built in Phase 2 part 1 (the
`supermarket-crm` job), not yet run live: the hub's EspoCRM connection
is stale.
- How reliable is a run of 50 queued actions? Not known until then.
### Phase 1: Content (today's pipeline, generalized) + Reddit ### Phase 1: Content (today's pipeline, generalized) + Reddit
@@ -451,12 +486,9 @@ in `internal/web/server.go` and an icon in `layout.html`. brain's fonts
(DM Sans, Plus Jakarta Sans) are named but not bundled, so the system font (DM Sans, Plus Jakarta Sans) are named but not bundled, so the system font
is used unless they're installed. is used unless they're installed.
**To pick this up:** try Phase 1 for real (the checklist above), fix what **Done since:** Phase 1 was tried for real (posting to X and LinkedIn
that turns up, then decide whether to merge `phase0-foundation` into `main` worked on 2026-11-21), merged into `main` and tagged `v0.1.0` on
and tag `v0.1.0`. Then Phase 2, Prospects → EspoCRM, which depends on the 2026-11-21. Phase 2 followed.
hub's EspoCRM tools (see Phase 0: `espocrm_search_records`,
`espocrm_get_record`, `espocrm_get_related_records`,
`espocrm_create_record`, `espocrm_update_record`, `espocrm_delete_record`).
The plan for Phase 1, as first written: The plan for Phase 1, as first written:
1. Port fetch → browse → select → generate → approve → publish into the web 1. Port fetch → browse → select → generate → approve → publish into the web
@@ -477,9 +509,10 @@ The plan for Phase 1, as first written:
**Started 2026-11-21** on branch `phase2-prospects`, after Phase 0 and 1 **Started 2026-11-21** on branch `phase2-prospects`, after Phase 0 and 1
were merged into `main` and tagged `v0.1.0`. **Parts 1 to 7 built, and were merged into `main` and tagged `v0.1.0`. **Parts 1 to 7 built, and
merged into `main` on 2026-11-22** (d23d5e2). Part 8 (Hugo pages per merged into `main` on 2026-11-22** (d23d5e2). Part 8 (Hugo pages per
signal) waits for Phase 5. Not yet tried against the live services: signal) was built in Phase 5, part 4. Stripe and Plausible were connected
discovery's web search, outreach's mailbox, Stripe and Plausible (no keys later on 2026-11-22. Not yet tried against the live services: discovery's
saved yet), and the CRM bridge, which waits on the Core's MCP hub. web search, outreach's mailbox, and the CRM bridge, which waits on the
Core's MCP hub.
**Reframed 2026-11-21 (the user's direction).** Phase 2 is built around **Reframed 2026-11-21 (the user's direction).** Phase 2 is built around
**buying signals**: hypotheses about why a company buys now, which are **buying signals**: hypotheses about why a company buys now, which are
@@ -1553,6 +1586,87 @@ admin. The docs don't say which scope the role list needs.
which sign-in is missing or expired. which sign-in is missing or expired.
Not tried for real: it waits on LinkedIn approving the page app. Not tried for real: it waits on LinkedIn approving the page app.
### Phase 7: What to write next, from what converts
**Planned 2026-11-24**, after comparing SEO with ChatSEO (which drafts
whole pages from Search Console alone). Supermarket already suggests
title changes (Changes), rewrites (What ranks → brief), new keywords
(Next keywords) and landing pages per signal, but each from Search
Console alone, in four places, and a page can only be retitled or
rewritten whole. Phase 7 ranks them by what turns visits into sign-ups,
adds suggestions from the funnel, puts them in one list, and adds a
section to an existing page.
**What can be measured per page today** (checked 2026-11-24 against
federated.computer's Plausible):
- *Visits by entry page*: Plausible's `visit:entry_page` (1,641 of the
last 30 days' visitors entered on `/`; then /partners/, /pricing/…).
- *Sign-up starts by entry page*: Plausible already records "Outbound Link:
Click" with the link (`event:props:url`). Clicks to
`enterprise.federated.computer/signup` (5) and
`cloud.federated.computer/signup` (2) in 30 days are sign-up starts, and
Plausible ties each to the page the visit began on.
- *Form leads by page*: the `Lead` goal, once it's added in Plausible
(Phase 6) and the forms are connected.
- *Not yet*: payments by page. Stripe knows a customer's signal only when
the shopping cart saves the UTM tags; it would need the landing page
too (`utm_content`, or a `landing_page` metadata key). Until then,
payments count per signal, not per page.
**Parts, in order, a commit after each:**
1. **Conversions by page.** Settings → Website & sales gets *What counts
as a sign-up*: link patterns for outbound clicks (default: any link
ending in `/signup`, found from the last 30 days' clicks and offered
for ticking), plus the `Lead` goal. The daily Plausible import adds,
per website and day: visitors, sign-up starts and leads by entry page
(a new `page_days` table, 16 months kept like Search Console's). The
page tables on What ranks, the audit and Sites show *Visits* and
*Sign-ups* next to clicks.
2. **Ranked by what converts.** Change candidates and *Push* pages are
ordered by expected sign-ups (impressions × the click rate a page one
result usually gets × the page's own visit-to-sign-up rate, or the
site's when the page has too few visits), not by impressions alone.
Flagged, wherever pages are listed: *traffic, no sign-ups* (at least
100 visits in 90 days and none) and *converts, hardly found* (a
sign-up rate in the site's top quarter, few impressions): the second
is the best case for a rewrite or new links to it.
3. **Suggestions from the funnel.**
- A signal with replies or interested people (origami.chat,
explee.com, email) but no landing page: *Build a landing page for
it*, with its numbers.
- An app or product named in replies: the reply texts Supermarket
already reads (email outreach), and explee.com's or origami.chat's
if their APIs give the text, are matched against the Software
Library's apps and the Inventory; one with no page of its own on the
site is suggested as a product page.
- A keyword picked but with no brief, and a brief with no page.
4. **One list: SEO → Next.** Every suggestion from parts 2 and 3, and the
existing ones (Changes' candidates, Push pages, Next keywords' picks),
in one ranked list, each with its reason in numbers and one button
that starts the existing flow (propose a title, write a brief, build a
landing page). Nothing is drafted until you press it; the brief still
asks its questions first. At most 10 shown; dismissing one hides it
for 90 days. It's a page under SEO (the module still opens on the
Morning check); the Monday report's section 3 links to it.
5. **Add a section to an existing page.** On a page (Sites → Sections and
pages), *Add a section*: choose one of the site's section types (faq,
table, features…) and where it goes; the AI drafts it from the page,
the profile and the Inventory, with the same rules as new pages (no
invented prices, customers or numbers; claims of experience to be
ticked; to-dos listed). The pull request changes only that page's
front matter, checked with a Hugo build. Suggested in the list when
the page's searches are questions (a FAQ) or name a competitor (a
comparison table).
**Decided 2026-11-24:** Supermarket suggests what counts as a sign-up
(the patterns above, from the links people really click) and the user
refines it: ticks or unticks the suggestions and adds their own patterns.
The SEO module keeps opening on the Morning check; *Next* is one more page
under SEO.
**Not in this phase:** writing drafts on its own (ChatSEO's way), images,
and competitors' live prices.
### Future enhancements ### Future enhancements
Not in any phase yet; picked up when the user asks. Not in any phase yet; picked up when the user asks.
+12
View File
@@ -613,6 +613,18 @@ ALTER TABLE site_pages ADD COLUMN live_note TEXT NOT NULL DEFAULT '';
// 25: a LinkedIn draft posts as the member ('') or the company page ('page'). // 25: a LinkedIn draft posts as the member ('') or the company page ('page').
` `
ALTER TABLE drafts ADD COLUMN linkedin_as TEXT NOT NULL DEFAULT ''; ALTER TABLE drafts ADD COLUMN linkedin_as TEXT NOT NULL DEFAULT '';
`,
// 26: what each page turns visits into (Plausible, by entry page).
`
CREATE TABLE page_days (
site TEXT NOT NULL, -- the Plausible site
date TEXT NOT NULL, -- YYYY-MM-DD
page TEXT NOT NULL, -- the entry page's path, e.g. /freescout/
visitors INTEGER NOT NULL DEFAULT 0,
signups INTEGER NOT NULL DEFAULT 0, -- visitors who clicked a sign-up link
leads INTEGER NOT NULL DEFAULT 0, -- visitors who sent a form (the Lead goal)
PRIMARY KEY (site, date, page)
);
`, `,
} }
+335
View File
@@ -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
}
+104
View File
@@ -0,0 +1,104 @@
package tracking
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"supermarket/internal/api/plausible"
)
// fakePlausible answers the page import's queries: clicked links, and
// visitors by day and entry page, for all visits, sign-ups and leads.
func fakePlausible(t *testing.T, queries *[]plausible.Query) *plausible.Client {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var q plausible.Query
json.NewDecoder(r.Body).Decode(&q)
*queries = append(*queries, q)
rows := []plausible.Row{}
goal := ""
for _, f := range q.Filters {
if f[1] == "event:goal" {
goal = fmt.Sprint(f[2])
}
}
switch {
case len(q.Dimensions) == 1 && q.Dimensions[0] == "event:props:url":
rows = []plausible.Row{{Dimensions: []string{"https://cloud.example/login"}, Metrics: []float64{6}},
{Dimensions: []string{"https://enterprise.example/signup?plan=x"}, Metrics: []float64{5}},
{Dimensions: []string{"https://docs.example/"}, Metrics: []float64{2}}}
case goal == "[Lead]":
rows = []plausible.Row{{Dimensions: []string{"2026-11-20", "/partners"}, Metrics: []float64{1}}}
case goal != "":
rows = []plausible.Row{{Dimensions: []string{"2026-11-20", "/freescout/"}, Metrics: []float64{2}}}
default:
rows = []plausible.Row{{Dimensions: []string{"2026-11-20", "/freescout/"}, Metrics: []float64{40}},
{Dimensions: []string{"2026-11-21", "/freescout/index.html"}, Metrics: []float64{10}},
{Dimensions: []string{"2026-11-21", "/partners/"}, Metrics: []float64{30}}}
}
json.NewEncoder(w).Encode(map[string]any{"results": rows})
}))
t.Cleanup(srv.Close)
return plausible.New(srv.URL, "k")
}
func TestImportPages(t *testing.T) {
d := openDB(t)
var queries []plausible.Query
c := fakePlausible(t, &queries)
links, err := OutboundLinks(context.Background(), c, "example.com")
if err != nil || len(links) != 3 {
t.Fatal(links, err)
}
var urls []string
for _, l := range links {
urls = append(urls, l.URL)
}
if s := LoadSignups(d, urls); s.Saved || len(s.Patterns) != 1 || s.Patterns[0] != "enterprise.example/signup" {
t.Errorf("suggested: %+v", s)
}
if _, err := ImportPages(context.Background(), d, c, []string{"example.com"}, now); err != nil {
t.Fatal(err)
}
pages, ok, err := Pages(d, "example.com", 90)
if err != nil || !ok {
t.Fatal(ok, err)
}
if f := pages["/freescout/"]; f.Visitors != 50 || f.Signups != 2 || f.Leads != 0 {
t.Errorf("freescout: %+v", f)
}
if p := pages["/partners/"]; p.Visitors != 30 || p.Leads != 1 || p.Rate() < 0.03 {
t.Errorf("partners: %+v", p)
}
// The suggestion was used for the sign-ups query.
found := false
for _, q := range queries {
for _, f := range q.Filters {
if f[1] == "event:props:url" && fmt.Sprint(f[2]) == "[enterprise.example/signup]" {
found = true
}
}
}
if !found {
t.Errorf("no sign-up filter in %+v", queries)
}
// The user's own definition replaces it, and the pages are read again.
if err := SaveSignups(d, []string{" Cloud.example/login ", "", "cloud.example/login"}); err != nil {
t.Fatal(err)
}
if s := LoadSignups(d, urls); !s.Saved || len(s.Patterns) != 1 || !s.Matches("https://CLOUD.example/login?x") || s.Matches("https://enterprise.example/signup") {
t.Errorf("saved: %+v", s)
}
if _, ok, _ := Pages(d, "example.com", 90); ok {
t.Error("the pages weren't reset")
}
if PathOf("https://www.example.com/FreeScout") != "/freescout/" {
t.Error("PathOf")
}
}
+2
View File
@@ -302,6 +302,7 @@ func (s *Server) seoPage(w http.ResponseWriter, r *http.Request) {
return return
} }
data["Ranks"] = ranks data["Ranks"] = ranks
data["Conv"] = s.pageConv(cur.URL)
} }
s.render(w, r, "seo", page{Title: "SEO", Nav: "seo/ranks", Data: data}) s.render(w, r, "seo", page{Title: "SEO", Nav: "seo/ranks", Data: data})
} }
@@ -552,6 +553,7 @@ func (s *Server) seoAuditPage(w http.ResponseWriter, r *http.Request) {
return return
} }
data["Audit"] = a data["Audit"] = a
data["Conv"] = s.pageConv(cur.URL)
if a != nil && a.Status == "done" { if a != nil && a.Status == "done" {
sev := r.URL.Query().Get("severity") sev := r.URL.Query().Get("severity")
var shown []seo.Issue var shown []seo.Issue
+6
View File
@@ -31,6 +31,7 @@ import (
"supermarket/internal/seo" "supermarket/internal/seo"
"supermarket/internal/signals" "supermarket/internal/signals"
"supermarket/internal/sites" "supermarket/internal/sites"
"supermarket/internal/tracking"
) )
//go:embed templates/*.html //go:embed templates/*.html
@@ -228,6 +229,7 @@ func (s *Server) Handler() (http.Handler, error) {
mux.HandleFunc("GET /settings/tracking", s.trackingPage) mux.HandleFunc("GET /settings/tracking", s.trackingPage)
mux.HandleFunc("POST /settings/tracking", s.trackingSave) mux.HandleFunc("POST /settings/tracking", s.trackingSave)
mux.HandleFunc("POST /settings/tracking/test/{source}", s.trackingTest) mux.HandleFunc("POST /settings/tracking/test/{source}", s.trackingTest)
mux.HandleFunc("POST /settings/tracking/signups", s.trackingSignups)
mux.HandleFunc("POST /settings/tracking/run/{source}", s.trackingRun) mux.HandleFunc("POST /settings/tracking/run/{source}", s.trackingRun)
mux.HandleFunc("GET /outreach", s.outreachPage) mux.HandleFunc("GET /outreach", s.outreachPage)
mux.HandleFunc("POST /outreach/draft", s.outreachDraft) mux.HandleFunc("POST /outreach/draft", s.outreachDraft)
@@ -394,6 +396,9 @@ func (s *Server) loadTemplates() error {
"dec1": func(f float64) string { return strconv.FormatFloat(f, 'f', 1, 64) }, "dec1": func(f float64) string { return strconv.FormatFloat(f, 'f', 1, 64) },
"pagePath": pagePath, "pagePath": pagePath,
"change": seo.Percent, "change": seo.Percent,
"conv": func(m map[string]tracking.PageNumbers, page string) tracking.PageNumbers {
return m[tracking.PathOf(page)]
},
"stage": signals.StageLabel, "stage": signals.StageLabel,
"channel": signals.ChannelLabel, "channel": signals.ChannelLabel,
"truncate": func(n int, s string) string { "truncate": func(n int, s string) string {
@@ -532,6 +537,7 @@ var flashes = map[string]string{
"keyword-picked": "Picked. Write its brief when you're ready.", "keyword-picked": "Picked. Write its brief when you're ready.",
"keyword-dismissed": "Dismissed: it's under Dismissed if you change your mind.", "keyword-dismissed": "Dismissed: it's under Dismissed if you change your mind.",
"keyword-back": "Back among the candidates.", "keyword-back": "Back among the candidates.",
"signups-saved": "Saved. The pages' sign-ups were read again with it.",
"audited": "The audit is done.", "audited": "The audit is done.",
"auditing": "Auditing. It reads up to 300 pages politely, so it takes a few minutes; this page updates when it's done.", "auditing": "Auditing. It reads up to 300 pages politely, so it takes a few minutes; this page updates when it's done.",
"no-data": "There isn't two weeks of Search Console data yet.", "no-data": "There isn't two weeks of Search Console data yet.",
+3
View File
@@ -87,6 +87,9 @@ func (s *Server) sitesPage(w http.ResponseWriter, r *http.Request) {
func (s *Server) renderSites(w http.ResponseWriter, r *http.Request, errMsg string) { func (s *Server) renderSites(w http.ResponseWriter, r *http.Request, errMsg string) {
all, cur := s.currentSite(r) all, cur := s.currentSite(r)
data := map[string]any{"Sites": all, "Current": cur, "Gitea": s.gitea() != nil, "Synced": siteSynced{}} data := map[string]any{"Sites": all, "Current": cur, "Gitea": s.gitea() != nil, "Synced": siteSynced{}}
if cur != nil {
data["Conv"] = s.pageConv(cur.URL)
}
if cur != nil && cur.Repo != "" { if cur != nil && cur.Repo != "" {
var synced siteSynced var synced siteSynced
if ok, _ := s.DB.GetJSON(siteSyncKey(cur.Repo), &synced); ok { if ok, _ := s.DB.GetJSON(siteSyncKey(cur.Repo), &synced); ok {
+2 -2
View File
@@ -59,7 +59,7 @@
<h2>Issues{{with $d.Severity}}: {{.}}s{{end}}</h2> <h2>Issues{{with $d.Severity}}: {{.}}s{{end}}</h2>
{{if $d.Shown}} {{if $d.Shown}}
<table class="list"> <table class="list">
<thead><tr><th></th><th>Issue</th><th>Page</th><th class="num">Clicks</th><th class="num">Impressions</th></tr></thead> <thead><tr><th></th><th>Issue</th><th>Page</th><th class="num">Clicks</th><th class="num">Impressions</th>{{if $d.Conv}}<th class="num" title="Visits that began on the page and went on to sign up or send a form, in 90 days">Sign-ups</th>{{end}}</tr></thead>
<tbody>{{range $d.Shown}}<tr> <tbody>{{range $d.Shown}}<tr>
<td><span class="badge {{if eq .Severity "error"}}failed{{else if eq .Severity "warning"}}scheduled{{end}}">{{.Severity}}</span></td> <td><span class="badge {{if eq .Severity "error"}}failed{{else if eq .Severity "warning"}}scheduled{{end}}">{{.Severity}}</span></td>
<td><strong>{{.Title}}</strong>{{with .Detail}}<br><span class="small">{{truncate 400 .}}</span>{{end}} <td><strong>{{.Title}}</strong>{{with .Detail}}<br><span class="small">{{truncate 400 .}}</span>{{end}}
@@ -70,7 +70,7 @@
<td class="small"><a href="{{.Page}}" target="_blank" rel="noopener noreferrer">{{pagePath .Page}}</a></td> <td class="small"><a href="{{.Page}}" target="_blank" rel="noopener noreferrer">{{pagePath .Page}}</a></td>
<td class="num">{{if .Traffic.Impressions}}{{num .Traffic.Clicks}}{{else}}<span class="muted">·</span>{{end}}</td> <td class="num">{{if .Traffic.Impressions}}{{num .Traffic.Clicks}}{{else}}<span class="muted">·</span>{{end}}</td>
<td class="num">{{if .Traffic.Impressions}}{{num .Traffic.Impressions}}{{else}}<span class="muted">·</span>{{end}}</td> <td class="num">{{if .Traffic.Impressions}}{{num .Traffic.Impressions}}{{else}}<span class="muted">·</span>{{end}}</td>
</tr>{{end}}</tbody> {{if $d.Conv}}{{with conv $d.Conv .Page}}<td class="num">{{if .Conversions}}<strong>{{num .Conversions}}</strong>{{else if .Visitors}}<span class="muted">0</span>{{else}}<span class="muted">·</span>{{end}}</td>{{end}}{{end}}</tr>{{end}}</tbody>
</table> </table>
{{with $d.More}}<p class="help">And {{.}} more.</p>{{end}} {{with $d.More}}<p class="help">And {{.}} more.</p>{{end}}
{{else}}<p class="help">No issues{{with $d.Severity}} of this kind{{end}}.</p>{{end}} {{else}}<p class="help">No issues{{with $d.Severity}} of this kind{{end}}.</p>{{end}}
+4 -4
View File
@@ -25,12 +25,12 @@
<section class="card"> <section class="card">
<h2>Protect</h2> <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> <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}} {{range .Protect}}<p><a href="{{.Page}}" target="_blank" rel="noopener noreferrer">{{pagePath .Page}}</a><br><span class="small">{{.Why}}{{if $d.Conv}}{{with conv $d.Conv .Page}} {{num .Visitors}} visits and {{num .Conversions}} sign-ups in 90 days.{{end}}{{end}}</span></p>{{else}}<p class="help">No page has clicks yet.</p>{{end}}
</section> </section>
<section class="card"> <section class="card">
<h2>Push</h2> <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> <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> {{range .Push}}<p><a href="{{.Page}}" target="_blank" rel="noopener noreferrer">{{pagePath .Page}}</a><br><span class="small">{{.Why}}{{if $d.Conv}}{{with conv $d.Conv .Page}} {{num .Visitors}} visits and {{num .Conversions}} sign-ups in 90 days.{{end}}{{end}}</span>
<form method="post" action="/seo/changes/page?site={{$d.Current.Index}}" class="inline" data-busy="Writing…"><input type="hidden" name="page" value="{{.Page}}"><input type="hidden" name="why" value="{{.Why}}"><button type="submit" class="link small">Propose a new title and description</button></form> <form method="post" action="/seo/changes/page?site={{$d.Current.Index}}" class="inline" data-busy="Writing…"><input type="hidden" name="page" value="{{.Page}}"><input type="hidden" name="why" value="{{.Why}}"><button type="submit" class="link small">Propose a new title and description</button></form>
· <form method="post" action="/seo/briefs?site={{$d.Current.Index}}" class="inline" data-busy="Writing the brief…"><input type="hidden" name="page" value="{{.Page}}"><button type="submit" class="link small">Write a brief to rewrite it</button></form></p>{{else}}<p class="help">No page sits on page one with few clicks. Good, or too little data.</p>{{end}} · <form method="post" action="/seo/briefs?site={{$d.Current.Index}}" class="inline" data-busy="Writing the brief…"><input type="hidden" name="page" value="{{.Page}}"><button type="submit" class="link small">Write a brief to rewrite it</button></form></p>{{else}}<p class="help">No page sits on page one with few clicks. Good, or too little data.</p>{{end}}
</section> </section>
@@ -39,8 +39,8 @@
<h2>Best pages</h2> <h2>Best pages</h2>
{{if .Pages}} {{if .Pages}}
<table class="list"> <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> <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>{{if $d.Conv}}<th class="num" title="Visits that began on the page, from Plausible">Visits</th><th class="num" title="Visits that began on the page and went on to sign up or send a form">Sign-ups</th>{{end}}</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> <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>{{if $d.Conv}}{{with conv $d.Conv .Page}}<td class="num">{{num .Visitors}}</td><td class="num">{{if .Conversions}}<strong>{{num .Conversions}}</strong>{{else}}<span class="muted">0</span>{{end}}</td>{{end}}{{end}}</tr>{{end}}</tbody>
</table> </table>
{{else}}<p class="help">No pages with data yet.</p>{{end}} {{else}}<p class="help">No pages with data yet.</p>{{end}}
+4 -4
View File
@@ -79,16 +79,16 @@
<h2>Pages</h2> <h2>Pages</h2>
{{with $d.SectionPages}} {{with $d.SectionPages}}
<div class="table-wrap"><table class="compact"> <div class="table-wrap"><table class="compact">
<thead><tr><th>Address</th><th>Title</th><th>Sections</th></tr></thead> <thead><tr><th>Address</th><th>Title</th><th>Sections</th>{{if $d.Conv}}<th class="num" title="Visits that began on the page, in 90 days (Plausible)">Visits</th><th class="num" title="Of those, the ones that went on to sign up or send a form">Sign-ups</th>{{end}}</tr></thead>
<tbody>{{range .}}<tr><td><a href="{{$d.Current.Base}}{{.Path}}" target="_blank" rel="noopener noreferrer">{{.Path}}</a>{{if .Draft}} <span class="badge draft">draft</span>{{end}}</td><td>{{.Title}}</td><td class="small">{{join .Types " · "}}</td></tr>{{end}}</tbody> <tbody>{{range .}}<tr><td><a href="{{$d.Current.Base}}{{.Path}}" target="_blank" rel="noopener noreferrer">{{.Path}}</a>{{if .Draft}} <span class="badge draft">draft</span>{{end}}</td><td>{{.Title}}</td><td class="small">{{join .Types " · "}}</td>{{if $d.Conv}}{{with conv $d.Conv .Path}}<td class="num">{{num .Visitors}}</td><td class="num">{{if .Conversions}}<strong>{{num .Conversions}}</strong>{{else}}<span class="muted">0</span>{{end}}</td>{{end}}{{end}}</tr>{{end}}</tbody>
</table></div> </table></div>
{{else}}<p class="help">No page is built from sections yet.</p>{{end}} {{else}}<p class="help">No page is built from sections yet.</p>{{end}}
{{with $d.OtherPages}} {{with $d.OtherPages}}
<details class="card"> <details class="card">
<summary>{{len .}} other pages, written in Markdown</summary> <summary>{{len .}} other pages, written in Markdown</summary>
<div class="table-wrap"><table class="compact"> <div class="table-wrap"><table class="compact">
<thead><tr><th>Address</th><th>Title</th></tr></thead> <thead><tr><th>Address</th><th>Title</th>{{if $d.Conv}}<th class="num">Visits</th><th class="num">Sign-ups</th>{{end}}</tr></thead>
<tbody>{{range .}}<tr><td>{{.Path}}{{if .Draft}} <span class="badge draft">draft</span>{{end}}</td><td>{{.Title}}</td></tr>{{end}}</tbody> <tbody>{{range .}}<tr><td>{{.Path}}{{if .Draft}} <span class="badge draft">draft</span>{{end}}</td><td>{{.Title}}</td>{{if $d.Conv}}{{with conv $d.Conv .Path}}<td class="num">{{num .Visitors}}</td><td class="num">{{if .Conversions}}<strong>{{num .Conversions}}</strong>{{else}}<span class="muted">0</span>{{end}}</td>{{end}}{{end}}</tr>{{end}}</tbody>
</table></div> </table></div>
</details> </details>
{{end}} {{end}}
+25
View File
@@ -61,6 +61,31 @@ metadata[utm_content] = optional: which message or post</pre>
<div class="actions"><button type="submit">Save</button></div> <div class="actions"><button type="submit">Save</button></div>
</form> </form>
{{if .PlausibleSet}}
<form method="post" action="/settings/tracking/signups" data-busy="Saving and reading the pages…">
<section class="card" id="signups">
<h3>What counts as a sign-up</h3>
<p class="small">Each page of your site is measured by what its visitors go on to do: click through to sign up, or send a form. Plausible records clicks on links to other sites (its <em>Outbound Link: Click</em> goal), and ties each to the page the visit began on. Say which of those links start a sign-up.{{if not .Signups.Saved}} <strong>Supermarket's suggestion is ticked</strong>: the links that look like a sign-up, a trial or a checkout. Change it and save to make it yours.{{end}}</p>
{{with .Links}}
<table class="list">
<thead><tr><th>A sign-up?</th><th>Link clicked, last 30 days</th><th class="num">Visitors</th></tr></thead>
<tbody>{{range .}}<tr>
<td><input type="checkbox" name="link" value="{{.URL}}" aria-label="{{.URL}} is a sign-up" {{if .Signup}}checked{{end}}></td>
<td class="small"><code>{{.URL}}</code></td><td class="num">{{num .Visitors}}</td>
</tr>{{end}}</tbody>
</table>
{{else}}<p class="help">No clicks on outbound links in the last 30 days, or Plausible couldn't be read.</p>{{end}}
<label>Other links that count (optional)
<textarea name="patterns" rows="3" placeholder="cloud.federated.computer/signup">{{.OwnPatterns}}</textarea>
<span class="help">One per line. A link counts if it contains the text, in any case: <code>/signup</code> counts every sign-up page on every site.</span>
</label>
<p class="small">Form leads count too, once your forms send Plausible's <code>Lead</code> goal (Sites → Lead forms).</p>
<div class="actions"><button type="submit">Save what counts</button></div>
{{template "last-run" .LastPages}}
</section>
</form>
{{end}}
{{end}}{{template "settings-end"}}{{end}} {{end}}{{template "settings-end"}}{{end}}
{{define "last-run"}}{{with .}} {{define "last-run"}}{{with .}}
+106
View File
@@ -3,7 +3,9 @@ package web
import ( import (
"context" "context"
"errors" "errors"
"fmt"
"net/http" "net/http"
"net/url"
"strconv" "strconv"
"strings" "strings"
"time" "time"
@@ -78,6 +80,39 @@ func (s *Server) renderTracking(w http.ResponseWriter, r *http.Request, errMsg s
lastS, _ := tracking.Last(s.DB, tracking.SourceStripe) lastS, _ := tracking.Last(s.DB, tracking.SourceStripe)
customers, _ := tracking.Customers(s.DB, 20) customers, _ := tracking.Customers(s.DB, 20)
set, _ := s.outreachSettings() set, _ := s.outreachSettings()
// The links visitors clicked, to say which are sign-ups.
var links []tracking.OutboundLink
if c := s.plausible(); c != nil {
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
for _, site := range s.sites() {
l, err := tracking.OutboundLinks(ctx, c, site)
if err == nil {
links = append(links, l...)
}
}
cancel()
}
var urls []string
for _, l := range links {
urls = append(urls, l.URL)
}
signups := tracking.LoadSignups(s.DB, urls)
var own []string // patterns that aren't one of the links, to edit as text
for i := range links {
links[i].Signup = signups.Matches(links[i].URL)
}
for _, p := range signups.Patterns {
listed := false
for _, l := range links {
if strings.EqualFold(patternOf(l.URL), p) {
listed = true
}
}
if !listed {
own = append(own, p)
}
}
lastPages, _ := tracking.Last(s.DB, "pages")
s.render(w, r, "tracking", page{Title: "Website & sales", Nav: "settings/tracking", Error: errMsg, Data: map[string]any{ s.render(w, r, "tracking", page{Title: "Website & sales", Nav: "settings/tracking", Error: errMsg, Data: map[string]any{
"PlausibleURL": s.plausibleURL(), "PlausibleURL": s.plausibleURL(),
"PlausibleKey": plausibleKey, "PlausibleKey": plausibleKey,
@@ -89,6 +124,10 @@ func (s *Server) renderTracking(w http.ResponseWriter, r *http.Request, errMsg s
"LastStripe": lastS, "LastStripe": lastS,
"Customers": customers, "Customers": customers,
"BookingFrom": set.BookingFrom, "BookingFrom": set.BookingFrom,
"Links": links,
"Signups": signups,
"OwnPatterns": strings.Join(own, "\n"),
"LastPages": lastPages,
}}) }})
} }
@@ -188,6 +227,9 @@ func (s *Server) runTracking(ctx context.Context, source string) error {
return errors.New("save the Plausible key first") return errors.New("save the Plausible key first")
} }
_, err := tracking.ImportPlausible(ctx, s.DB, c, s.sites(), now) _, err := tracking.ImportPlausible(ctx, s.DB, c, s.sites(), now)
if _, perr := tracking.ImportPages(ctx, s.DB, c, s.sites(), now); perr != nil && err == nil {
err = fmt.Errorf("pages: %w", perr)
}
return err return err
case tracking.SourceStripe: case tracking.SourceStripe:
c := s.stripe() c := s.stripe()
@@ -235,3 +277,67 @@ func (s *Server) RunTracking(ctx context.Context) {
} }
} }
} }
// patternOf is the pattern a ticked link saves as: its host and path.
func patternOf(link string) string {
if p := tracking.SuggestSignups([]string{link}); len(p) > 0 {
return p[0]
}
if u, err := url.Parse(link); err == nil && u.Host != "" {
return strings.ToLower(u.Host + strings.TrimRight(u.Path, "/"))
}
return strings.ToLower(link)
}
// trackingSignups saves what counts as a sign-up, and reads the pages
// again with it.
func (s *Server) trackingSignups(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
var pats []string
for _, l := range r.PostForm["link"] {
pats = append(pats, patternOf(l))
}
pats = append(pats, strings.Split(r.PostFormValue("patterns"), "\n")...)
if err := tracking.SaveSignups(s.DB, pats); err != nil {
s.serverError(w, err)
return
}
if c := s.plausible(); c != nil {
ctx, cancel := context.WithTimeout(r.Context(), 3*time.Minute)
_, err := tracking.ImportPages(ctx, s.DB, c, s.sites(), time.Now())
cancel()
if err != nil {
s.renderTracking(w, r, "Saved, but reading the pages again failed: "+err.Error())
return
}
}
redirect(w, r, "/settings/tracking#signups", "signups-saved")
}
// convDays is the period the page tables show visits and sign-ups for, as
// What ranks shows Search Console's.
const convDays = 90
// pageConv is a website's visits, sign-ups and leads by page over the last
// convDays, or nil before Plausible's pages were read.
func (s *Server) pageConv(siteURL string) map[string]tracking.PageNumbers {
p, _ := profile.Load(s.DB)
if p == nil {
return nil
}
want := strings.TrimRight(strings.ToLower(strings.TrimSpace(siteURL)), "/")
for _, w := range p.Websites {
if strings.TrimRight(strings.ToLower(strings.TrimSpace(w.URL)), "/") != want {
continue
}
pages, ok, err := tracking.Pages(s.DB, tracking.SiteID(w), convDays)
if err != nil || !ok {
return nil
}
return pages
}
return nil
}