diff --git a/PLAN.md b/PLAN.md index 625388a..2ca9787 100644 --- a/PLAN.md +++ b/PLAN.md @@ -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 | | 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 | -| 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 | | 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 | | 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 `/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 @@ -300,7 +332,7 @@ What item 8 turned up: the Core's developer: it isn't known yet whether the hub blocks them for 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 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. - ~~Does `hermes config set` write nested `mcp_servers.*.headers` keys correctly?~~ Yes. - - What EspoCRM tools does the hub expose? - - Can Hermes cron jobs call MCP tools? - - How reliable is a run of 50 queued actions? + - ~~What EspoCRM tools does the hub expose?~~ Six generic record tools + (above). Answered 2026-11-20. + - 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 @@ -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 is used unless they're installed. -**To pick this up:** try Phase 1 for real (the checklist above), fix what -that turns up, then decide whether to merge `phase0-foundation` into `main` -and tag `v0.1.0`. Then Phase 2, Prospects → EspoCRM, which depends on the -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`). +**Done since:** Phase 1 was tried for real (posting to X and LinkedIn +worked on 2026-11-21), merged into `main` and tagged `v0.1.0` on +2026-11-21. Phase 2 followed. The plan for Phase 1, as first written: 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 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 -signal) waits for Phase 5. Not yet tried against the live services: -discovery's web search, outreach's mailbox, Stripe and Plausible (no keys -saved yet), and the CRM bridge, which waits on the Core's MCP hub. +signal) was built in Phase 5, part 4. Stripe and Plausible were connected +later on 2026-11-22. Not yet tried against the live services: discovery's +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 **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. 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 Not in any phase yet; picked up when the user asks. diff --git a/internal/db/db.go b/internal/db/db.go index 7c3c5f3..6d06714 100644 --- a/internal/db/db.go +++ b/internal/db/db.go @@ -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'). ` 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) +); `, } diff --git a/internal/tracking/pages.go b/internal/tracking/pages.go new file mode 100644 index 0000000..1f9033c --- /dev/null +++ b/internal/tracking/pages.go @@ -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 +} diff --git a/internal/tracking/pages_test.go b/internal/tracking/pages_test.go new file mode 100644 index 0000000..3d2bb15 --- /dev/null +++ b/internal/tracking/pages_test.go @@ -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") + } +} diff --git a/internal/web/seo.go b/internal/web/seo.go index 738624c..e6dd690 100644 --- a/internal/web/seo.go +++ b/internal/web/seo.go @@ -302,6 +302,7 @@ func (s *Server) seoPage(w http.ResponseWriter, r *http.Request) { return } data["Ranks"] = ranks + data["Conv"] = s.pageConv(cur.URL) } 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 } data["Audit"] = a + data["Conv"] = s.pageConv(cur.URL) if a != nil && a.Status == "done" { sev := r.URL.Query().Get("severity") var shown []seo.Issue diff --git a/internal/web/server.go b/internal/web/server.go index 0af3851..765557e 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -31,6 +31,7 @@ import ( "supermarket/internal/seo" "supermarket/internal/signals" "supermarket/internal/sites" + "supermarket/internal/tracking" ) //go:embed templates/*.html @@ -228,6 +229,7 @@ func (s *Server) Handler() (http.Handler, error) { mux.HandleFunc("GET /settings/tracking", s.trackingPage) mux.HandleFunc("POST /settings/tracking", s.trackingSave) 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("GET /outreach", s.outreachPage) mux.HandleFunc("POST /outreach/draft", s.outreachDraft) @@ -394,8 +396,11 @@ func (s *Server) loadTemplates() error { "dec1": func(f float64) string { return strconv.FormatFloat(f, 'f', 1, 64) }, "pagePath": pagePath, "change": seo.Percent, - "stage": signals.StageLabel, - "channel": signals.ChannelLabel, + "conv": func(m map[string]tracking.PageNumbers, page string) tracking.PageNumbers { + return m[tracking.PathOf(page)] + }, + "stage": signals.StageLabel, + "channel": signals.ChannelLabel, "truncate": func(n int, s string) string { r := []rune(s) if len(r) <= n { @@ -532,6 +537,7 @@ var flashes = map[string]string{ "keyword-picked": "Picked. Write its brief when you're ready.", "keyword-dismissed": "Dismissed: it's under Dismissed if you change your mind.", "keyword-back": "Back among the candidates.", + "signups-saved": "Saved. The pages' sign-ups were read again with it.", "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.", "no-data": "There isn't two weeks of Search Console data yet.", diff --git a/internal/web/sites.go b/internal/web/sites.go index 0828708..a17bcd1 100644 --- a/internal/web/sites.go +++ b/internal/web/sites.go @@ -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) { all, cur := s.currentSite(r) 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 != "" { var synced siteSynced if ok, _ := s.DB.GetJSON(siteSyncKey(cur.Repo), &synced); ok { diff --git a/internal/web/templates/seo-audit.html b/internal/web/templates/seo-audit.html index 4fd7afe..f7b5146 100644 --- a/internal/web/templates/seo-audit.html +++ b/internal/web/templates/seo-audit.html @@ -59,7 +59,7 @@

Issues{{with $d.Severity}}: {{.}}s{{end}}

{{if $d.Shown}} - + {{if $d.Conv}}{{end}}{{range $d.Shown}} - {{end}} + {{if $d.Conv}}{{with conv $d.Conv .Page}}{{end}}{{end}}{{end}}
IssuePageClicksImpressions
IssuePageClicksImpressionsSign-ups
{{.Severity}} {{.Title}}{{with .Detail}}
{{truncate 400 .}}{{end}} @@ -70,7 +70,7 @@
{{pagePath .Page}} {{if .Traffic.Impressions}}{{num .Traffic.Clicks}}{{else}}·{{end}} {{if .Traffic.Impressions}}{{num .Traffic.Impressions}}{{else}}·{{end}}
{{if .Conversions}}{{num .Conversions}}{{else if .Visitors}}0{{else}}·{{end}}
{{with $d.More}}

And {{.}} more.

{{end}} {{else}}

No issues{{with $d.Severity}} of this kind{{end}}.

{{end}} diff --git a/internal/web/templates/seo.html b/internal/web/templates/seo.html index b39752c..49128f3 100644 --- a/internal/web/templates/seo.html +++ b/internal/web/templates/seo.html @@ -25,12 +25,12 @@

Protect

They carry the clicks: don't rewrite them for fun, don't change their address, look at them first.

- {{range .Protect}}

{{pagePath .Page}}
{{.Why}}

{{else}}

No page has clicks yet.

{{end}} + {{range .Protect}}

{{pagePath .Page}}
{{.Why}}{{if $d.Conv}}{{with conv $d.Conv .Page}} {{num .Visitors}} visits and {{num .Conversions}} sign-ups in 90 days.{{end}}{{end}}

{{else}}

No page has clicks yet.

{{end}}

Push

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.

- {{range .Push}}

{{pagePath .Page}}
{{.Why}} + {{range .Push}}

{{pagePath .Page}}
{{.Why}}{{if $d.Conv}}{{with conv $d.Conv .Page}} {{num .Visitors}} visits and {{num .Conversions}} sign-ups in 90 days.{{end}}{{end}}

·

{{else}}

No page sits on page one with few clicks. Good, or too little data.

{{end}}
@@ -39,8 +39,8 @@

Best pages

{{if .Pages}} - - {{range .Pages}}{{end}} + {{if $d.Conv}}{{end}} + {{range .Pages}}{{if $d.Conv}}{{with conv $d.Conv .Page}}{{end}}{{end}}{{end}}
PageClicksImpressionsClick ratePosition
{{pagePath .Page}}{{num .Clicks}}{{num .Impressions}}{{dec1 .CTR}}%{{dec1 .Position}}
PageClicksImpressionsClick ratePositionVisitsSign-ups
{{pagePath .Page}}{{num .Clicks}}{{num .Impressions}}{{dec1 .CTR}}%{{dec1 .Position}}{{num .Visitors}}{{if .Conversions}}{{num .Conversions}}{{else}}0{{end}}
{{else}}

No pages with data yet.

{{end}} diff --git a/internal/web/templates/sites.html b/internal/web/templates/sites.html index 8229f62..bec4bd7 100644 --- a/internal/web/templates/sites.html +++ b/internal/web/templates/sites.html @@ -79,16 +79,16 @@

Pages

{{with $d.SectionPages}}
- - {{range .}}{{end}} + {{if $d.Conv}}{{end}} + {{range .}}{{if $d.Conv}}{{with conv $d.Conv .Path}}{{end}}{{end}}{{end}}
AddressTitleSections
{{.Path}}{{if .Draft}} draft{{end}}{{.Title}}{{join .Types " · "}}
AddressTitleSectionsVisitsSign-ups
{{.Path}}{{if .Draft}} draft{{end}}{{.Title}}{{join .Types " · "}}{{num .Visitors}}{{if .Conversions}}{{num .Conversions}}{{else}}0{{end}}
{{else}}

No page is built from sections yet.

{{end}} {{with $d.OtherPages}}
{{len .}} other pages, written in Markdown
- - {{range .}}{{end}} + {{if $d.Conv}}{{end}} + {{range .}}{{if $d.Conv}}{{with conv $d.Conv .Path}}{{end}}{{end}}{{end}}
AddressTitle
{{.Path}}{{if .Draft}} draft{{end}}{{.Title}}
AddressTitleVisitsSign-ups
{{.Path}}{{if .Draft}} draft{{end}}{{.Title}}{{num .Visitors}}{{if .Conversions}}{{num .Conversions}}{{else}}0{{end}}
{{end}} diff --git a/internal/web/templates/tracking.html b/internal/web/templates/tracking.html index 4a5bbbc..e5e1b37 100644 --- a/internal/web/templates/tracking.html +++ b/internal/web/templates/tracking.html @@ -61,6 +61,31 @@ metadata[utm_content] = optional: which message or post
+ +{{if .PlausibleSet}} +
+
+

What counts as a sign-up

+

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 Outbound Link: Click goal), and ties each to the page the visit began on. Say which of those links start a sign-up.{{if not .Signups.Saved}} Supermarket's suggestion is ticked: the links that look like a sign-up, a trial or a checkout. Change it and save to make it yours.{{end}}

+ {{with .Links}} + + + {{range .}} + + + {{end}} +
A sign-up?Link clicked, last 30 daysVisitors
{{.URL}}{{num .Visitors}}
+ {{else}}

No clicks on outbound links in the last 30 days, or Plausible couldn't be read.

{{end}} + +

Form leads count too, once your forms send Plausible's Lead goal (Sites → Lead forms).

+
+ {{template "last-run" .LastPages}} +
+
+{{end}} {{end}}{{template "settings-end"}}{{end}} {{define "last-run"}}{{with .}} diff --git a/internal/web/tracking.go b/internal/web/tracking.go index ebe9599..9648d48 100644 --- a/internal/web/tracking.go +++ b/internal/web/tracking.go @@ -3,7 +3,9 @@ package web import ( "context" "errors" + "fmt" "net/http" + "net/url" "strconv" "strings" "time" @@ -78,6 +80,39 @@ func (s *Server) renderTracking(w http.ResponseWriter, r *http.Request, errMsg s lastS, _ := tracking.Last(s.DB, tracking.SourceStripe) customers, _ := tracking.Customers(s.DB, 20) 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{ "PlausibleURL": s.plausibleURL(), "PlausibleKey": plausibleKey, @@ -89,6 +124,10 @@ func (s *Server) renderTracking(w http.ResponseWriter, r *http.Request, errMsg s "LastStripe": lastS, "Customers": customers, "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") } _, 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 case tracking.SourceStripe: 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 +}