From 062fcf2e5932b691b29ff9d714eda827c8b97135 Mon Sep 17 00:00:00 2001 From: David Young Date: Sun, 22 Nov 2026 14:19:55 -0700 Subject: [PATCH] Phase 5 part 4: landing pages per buying signal MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Each signal's page lists its landing pages with their Gitea status, live address and 30-day visitors from Plausible, and builds a new one. Pages can be duplicated as variants (B, C…, with their own utm_content), taken off the site through a pull request that deletes the file, or have their pull request closed. The scorecard counts live pages. Schema 23. Co-Authored-By: Claude Opus 5.5 --- PLAN.md | 24 ++++- TEST.md | 20 ++++ internal/api/gitea/client.go | 5 + internal/db/db.go | 6 ++ internal/hugorepo/repo.go | 13 +++ internal/sites/compose.go | 138 +++++++++++++++++++++++-- internal/sites/compose_test.go | 6 +- internal/sites/pages.go | 82 ++++++++++++--- internal/tracking/tracking.go | 37 +++++++ internal/web/signals.go | 81 +++++++++++++++ internal/web/sitepages.go | 83 +++++++++++++-- internal/web/sites_test.go | 138 +++++++++++++++++++++++++ internal/web/static/app.css | 7 ++ internal/web/templates/layout.html | 2 + internal/web/templates/signal.html | 42 ++++++++ internal/web/templates/signals.html | 2 +- internal/web/templates/sites-page.html | 21 ++++ 17 files changed, 674 insertions(+), 33 deletions(-) diff --git a/PLAN.md b/PLAN.md index 2064930..3db9b94 100644 --- a/PLAN.md +++ b/PLAN.md @@ -658,7 +658,8 @@ data. Each becomes an adapter behind a `leadsource` interface. - **Still to do.** The cart has to save the UTM tags in the Checkout Session's metadata. Settings → Website & sales says how. 8. **Later, with Phase 5 (sites)**: Hugo pages per signal, created, - duplicated or deleted from the scorecard, through Gitea PRs. + duplicated or deleted from the scorecard, through Gitea PRs. **Built in + Phase 5's part 4 (2026-11-22).** Inbound: the lead-form component (Phase 5) queues a Lead the same way, tagged with the signal from its UTM campaign. @@ -1303,6 +1304,27 @@ a branch. Pages show merged or closed from Gitea. Not yet tried against the live AI or the real repository: a build is a paid AI call and pushes a branch. +**Part 4 built (2026-11-22; schema 23, the removal pull request's +columns).** Each signal's page has a *Landing pages* section: its pages on +every site (variants after their original), their status from Gitea +(refreshed on view), the live address, and each live page's visitors over +30 days from Plausible (`event:page`, per page, never per person). A form +there builds a landing page for the signal (the page builder, with the +signal preset). Per page: +- *Duplicate as a variant*: a copy at the original's address plus `-b`, + `-c`… (variants B, C; the original becomes A), optionally rewritten from + notes on what to change. A variant's links to the site also carry + `utm_content=`, so sign-ups that keep the tags can be told + apart; the original's links stay as they are, so a live page needn't + change when a variant is added. +- *Remove from the site* (published pages): a pull request on + `supermarket/remove-site-page-` deleting the file, checked with a + build; merged, the page is *removed*; closed, it's back to *merged*. +- *Close the pull request*: closes an open one (adding or removing) on + Gitea without merging. +The scorecard shows how many landing pages each signal has live. Phase 2's +part 8 is done by this. + ### Future enhancements Not in any phase yet; picked up when the user asks. diff --git a/TEST.md b/TEST.md index 5e9bcda..e91eea9 100644 --- a/TEST.md +++ b/TEST.md @@ -547,6 +547,26 @@ Throughout, also notice: - [ ] After merging on Gitea, the page shows *merged* and can't be edited. - [ ] *Delete* forgets it here; the branch and pull request stay on Gitea. +### Landing pages per signal + +- [ ] A signal's page has a *Landing pages* section; with none, it says so + and offers *Build a landing page for it*, which opens the new page + with the signal set. +- [ ] Once its pull request is merged on Gitea, the signal's page shows it + as merged, with its live address and its visitors over 30 days (match + them against Plausible's page report). +- [ ] The scorecard shows "1 page" (or more) next to the signal. +- [ ] *Duplicate as a variant* makes variant B at the original's address + plus `-b`; the original is marked A. Its links carry + `utm_content=`; the original's don't change. +- [ ] With notes ("a shorter page, price in the hero"), the variant is + rewritten to match; without, it's an exact copy to edit. +- [ ] *Close the pull request* closes it on Gitea without merging. +- [ ] *Remove from the site* opens a pull request that deletes only that + page's file; merged, the page shows *removed* and the scorecard + stops counting it. Closing that pull request instead puts it back to + *merged*. + ## 9. Search - [ ] Searching for an inventory entry, a fetched item, a post, a prospect diff --git a/internal/api/gitea/client.go b/internal/api/gitea/client.go index 4d46d36..87bf562 100644 --- a/internal/api/gitea/client.go +++ b/internal/api/gitea/client.go @@ -139,6 +139,11 @@ func (c *Client) GetPull(ctx context.Context, full string, n int64) (*Pull, erro return &p, nil } +// ClosePull closes a pull request without merging it. +func (c *Client) ClosePull(ctx context.Context, full string, n int64) error { + return c.do(ctx, http.MethodPatch, fmt.Sprintf("/repos/%s/pulls/%d", escapeFull(full), n), map[string]string{"state": "closed"}, nil) +} + func escapeFull(full string) string { owner, name, _ := strings.Cut(full, "/") return url.PathEscape(owner) + "/" + url.PathEscape(name) diff --git a/internal/db/db.go b/internal/db/db.go index 21ad4fb..47080da 100644 --- a/internal/db/db.go +++ b/internal/db/db.go @@ -596,6 +596,12 @@ CREATE TABLE site_pages ( merged_at TEXT ); CREATE INDEX site_pages_by_site ON site_pages (site, created_at); +`, + // 23: taking a published page off the site, through its own pull request. + ` +ALTER TABLE site_pages ADD COLUMN removal_branch TEXT NOT NULL DEFAULT ''; +ALTER TABLE site_pages ADD COLUMN removal_pr_number INTEGER NOT NULL DEFAULT 0; +ALTER TABLE site_pages ADD COLUMN removal_pr_url TEXT NOT NULL DEFAULT ''; `, } diff --git a/internal/hugorepo/repo.go b/internal/hugorepo/repo.go index a5d0195..e434fd8 100644 --- a/internal/hugorepo/repo.go +++ b/internal/hugorepo/repo.go @@ -547,6 +547,19 @@ func (r *Repo) WriteFile(rel, content string) error { return nil } +// RemoveFile deletes a file from the working copy, to be committed. +func (r *Repo) RemoveFile(rel string) error { + p, err := r.inside(rel) + if err != nil { + return err + } + if err := os.Remove(p); err != nil { + return err + } + r.touched = append(r.touched, filepath.ToSlash(rel)) + return nil +} + // ConfigFile is the site's main Hugo configuration file, or "". func (r *Repo) ConfigFile() string { for _, name := range []string{"hugo.toml", "hugo.yaml", "hugo.yml", "config.toml", "config.yaml", "config.yml", diff --git a/internal/sites/compose.go b/internal/sites/compose.go index 2e5c35d..ecd8772 100644 --- a/internal/sites/compose.go +++ b/internal/sites/compose.go @@ -285,8 +285,9 @@ var mdLink = regexp.MustCompile(`\]\(([^)\s]+)\)`) // the site has (an error otherwise); fields the type isn't known to use, // and links to pages the site doesn't have, are warnings. With a campaign, // links to the site get utm_campaign (and utm_medium=landing) so visits -// and sign-ups count for the signal. -func Check(c *Catalog, sectionsYAML, siteURL, campaign string) (*Checked, error) { +// and sign-ups count for the signal, and utm_content when given (which +// variant of the page they came from). +func Check(c *Catalog, sectionsYAML, siteURL, campaign, content string) (*Checked, error) { var doc yaml.Node if err := yaml.Unmarshal([]byte(sectionsYAML), &doc); err != nil { return nil, fmt.Errorf("the sections aren't valid YAML: %v", err) @@ -341,7 +342,7 @@ func Check(c *Catalog, sectionsYAML, siteURL, campaign string) (*Checked, error) out.Warnings = append(out.Warnings, fmt.Sprintf("Section %d (%s) links to %s, which isn't a page on the site.", i+1, t.Name, target)) } if own && campaign != "" { - n.Value = tag(n.Value, campaign) + n.Value = tag(n.Value, campaign, content) } case "type", "style", "id", "image", "photo", "icon", "logImage", "video": default: @@ -353,7 +354,7 @@ func Check(c *Catalog, sectionsYAML, siteURL, campaign string) (*Checked, error) out.Warnings = append(out.Warnings, fmt.Sprintf("Section %d (%s) links to %s, which isn't a page on the site.", i+1, t.Name, target)) } if own && campaign != "" { - return strings.Replace(m, "("+link+")", "("+tag(link, campaign)+")", 1) + return strings.Replace(m, "("+link+")", "("+tag(link, campaign, content)+")", 1) } return m }) @@ -437,8 +438,9 @@ func ownPath(link string, site *url.URL) (string, bool) { return p, true } -// tag adds the campaign to a link (tags already there win). -func tag(link, campaign string) string { +// tag adds the campaign (and content) to a link. Tags already there win, +// except utm_content, which follows the page's variant. +func tag(link, campaign, content string) string { u, err := url.Parse(link) if err != nil { return link @@ -450,6 +452,9 @@ func tag(link, campaign string) string { if q.Get("utm_medium") == "" { q.Set("utm_medium", "landing") } + if content != "" { + q.Set("utm_content", content) + } u.RawQuery = q.Encode() return u.String() } @@ -585,3 +590,124 @@ func ConfirmedAll(claims, confirmed []string) error { } return nil } + +// Content is the utm_content a variant's links carry ("for-churches-b"), +// so its sign-ups can be told from the original's; the original (A) and +// pages without variants carry none. +func Content(p *SitePage) string { + if p.Source.VariantOf == 0 || p.Path == "" { + return "" + } + return strings.ReplaceAll(strings.Trim(p.Path, "/"), "/", "-") +} + +// Variant makes a copy of a page to test against it: the same sections at +// its own address (the original's with -b, -c…), a draft until pushed. +func Variant(d *db.DB, orig *SitePage) (*SitePage, error) { + rootID := orig.Root() + root := orig + if rootID != orig.ID { + r, err := GetPage(d, rootID) + if err != nil { + return nil, err + } + root = r + } + all, err := Pages(d, orig.Site) + if err != nil { + return nil, err + } + used := map[string]bool{} + letters := 1 // the root is A + for _, p := range all { + used[p.Path] = true + if p.Source.VariantOf == rootID { + letters++ + } + } + letter := string(rune('A' + letters)) + base := strings.TrimSuffix(root.Path, "/") + path := base + "-" + strings.ToLower(letter) + "/" + for n := 2; used[path]; n++ { + path = fmt.Sprintf("%s-%s%d/", base, strings.ToLower(letter), n) + } + v := &SitePage{Site: orig.Site, Repo: orig.Repo, Kind: orig.Kind, Source: orig.Source, Notes: orig.Notes, Path: path, + Title: orig.Title, Description: orig.Description, Sections: orig.Sections, Needs: orig.Needs, Warnings: orig.Warnings, + Claims: orig.Claims, Status: PageDraft} + v.Source.VariantOf, v.Source.Variant = rootID, letter + if root.Source.Variant == "" { + root.Source.Variant = "A" + if err := SavePage(d, root); err != nil { + return nil, err + } + } + return v, SavePage(d, v) +} + +// Remove opens a pull request that takes a published page off the site. +func Remove(ctx context.Context, d *db.DB, ap *seo.Applier, p *SitePage) error { + if p.Status != PageMerged { + return errors.New("only a page that's on the site can be taken off it") + } + if p.File == "" { + return errors.New("Supermarket doesn't know this page's file") + } + wc, full, published, err := ap.WorkingCopy(ctx) + if err != nil { + return err + } + defer wc.Release() + if !wc.Exists(p.File) { + return fmt.Errorf("%s isn't on the published branch any more", p.File) + } + branch := fmt.Sprintf("supermarket/remove-site-page-%d", p.ID) + if err := wc.NewBranch(ctx, branch); err != nil { + return err + } + if err := wc.RemoveFile(p.File); err != nil { + return err + } + note := "Not checked with a build: there's no Hugo in Supermarket's image." + if hugorepo.HugoVersion(ctx) != "" { + out, err := wc.Build(ctx) + if err != nil { + return fmt.Errorf("without this page, %w", err) + } + os.RemoveAll(out) + note = "Checked with a build: the site builds without it." + } + subject := fmt.Sprintf("Sites: remove %s", p.Path) + if err := wc.CommitAndPush(ctx, branch, subject); err != nil { + return err + } + body := fmt.Sprintf("Takes **%s** (`%s`, %s) off the site, as asked in Supermarket.\n\nLinks to it from elsewhere (outreach, posts, other pages) will stop working; consider a redirect (an `aliases:` entry on another page) if it was shared.\n\n%s\n\nMerging removes it from the live site.", + p.Title, p.Path, p.File, note) + pull, err := ap.Gitea.OpenPull(ctx, full, branch, published, subject, body) + if err != nil { + return err + } + p.RemovalBranch, p.RemovalPRNumber, p.RemovalPRURL, p.Status, p.Error = branch, pull.Number, pull.HTMLURL, PageRemoving, "" + return SavePage(d, p) +} + +// ClosePR closes a page's open pull request (adding it, or removing it) +// without merging. +func ClosePR(ctx context.Context, d *db.DB, g interface { + ClosePull(ctx context.Context, full string, n int64) error +}, full string, p *SitePage) error { + switch p.Status { + case PagePR: + if err := g.ClosePull(ctx, full, p.PRNumber); err != nil { + return err + } + p.Status = PageClosed + case PageRemoving: + if err := g.ClosePull(ctx, full, p.RemovalPRNumber); err != nil { + return err + } + p.Status, p.RemovalPRNumber, p.RemovalPRURL = PageMerged, 0, "" + default: + return errors.New("there's no open pull request to close") + } + return SavePage(d, p) +} diff --git a/internal/sites/compose_test.go b/internal/sites/compose_test.go index c2f0e7c..f248fae 100644 --- a/internal/sites/compose_test.go +++ b/internal/sites/compose_test.go @@ -50,7 +50,7 @@ func TestCheck(t *testing.T) { - q: Why? a: "[Read more](/missing/)" ` - ch, err := Check(c, in, "https://site.example/", "churches") + ch, err := Check(c, in, "https://site.example/", "churches", "") if err != nil { t.Fatal(err) } @@ -88,12 +88,12 @@ func TestCheck(t *testing.T) { "- type: hero\n title: [x\n": "valid YAML", "": "must be a list", } { - if _, err := Check(c, in, "https://site.example/", ""); err == nil || !strings.Contains(err.Error(), want) { + if _, err := Check(c, in, "https://site.example/", "", ""); err == nil || !strings.Contains(err.Error(), want) { t.Errorf("%q: %v, want %q", in, err, want) } } // Without a campaign, links stay as they are. - ch, _ = Check(c, "- type: hero\n ctas:\n - url: /pricing/\n", "https://site.example/", "") + ch, _ = Check(c, "- type: hero\n ctas:\n - url: /pricing/\n", "https://site.example/", "", "") if strings.Contains(ch.Sections, "utm_") { t.Errorf("tagged without a campaign: %s", ch.Sections) } diff --git a/internal/sites/pages.go b/internal/sites/pages.go index 6750814..4ff62f1 100644 --- a/internal/sites/pages.go +++ b/internal/sites/pages.go @@ -10,13 +10,15 @@ import ( // Page statuses. const ( - PageDraft = "draft" // composed; the user reviews it - PageWorking = "working" // being pushed - PagePushed = "pushed" // on its branch, with a preview; no pull request yet - PagePR = "pr" // a pull request is open - PageMerged = "merged" // merged: published - PageClosed = "closed" // the pull request was closed without merging - PageFailed = "failed" // the last push failed; Error says why + PageDraft = "draft" // composed; the user reviews it + PageWorking = "working" // being pushed + PagePushed = "pushed" // on its branch, with a preview; no pull request yet + PagePR = "pr" // a pull request is open + PageMerged = "merged" // merged: published + PageClosed = "closed" // the pull request was closed without merging + PageFailed = "failed" // the last push failed; Error says why + PageRemoving = "removing" // a pull request taking it off the site is open + PageRemoved = "removed" // that pull request was merged: it's off the site ) // Kinds of page, with what each is for (shown to the user and the AI). @@ -58,6 +60,8 @@ type Source struct { Competitor int64 `json:"competitor,omitempty"` // an Inventory entry Signal int64 `json:"signal,omitempty"` // a buying signal Brief int64 `json:"brief,omitempty"` // an SEO brief + VariantOf int64 `json:"variant_of,omitempty"` // the page this one is a variant of + Variant string `json:"variant,omitempty"` // "B", "C"…; the first page is "A" } // SitePage is a page built from the site's sections. @@ -85,6 +89,22 @@ type SitePage struct { CreatedAt time.Time UpdatedAt time.Time MergedAt time.Time + + RemovalBranch string + RemovalPRNumber int64 + RemovalPRURL string +} + +// Live says whether the page is on the published site. +func (p *SitePage) Live() bool { return p.Status == PageMerged || p.Status == PageRemoving } + +// Root is the page variants are made from: itself, or the page it's a +// variant of. +func (p *SitePage) Root() int64 { + if p.Source.VariantOf != 0 { + return p.Source.VariantOf + } + return p.ID } // Editable says whether the user can still change the page here. @@ -93,7 +113,8 @@ func (p *SitePage) Editable() bool { } const pageCols = `id, site, repo, kind, source, notes, path, title, description, sections, needs, warnings, claims, - status, branch, file, pr_number, pr_url, note, error, created_at, updated_at, merged_at` + status, branch, file, pr_number, pr_url, note, error, created_at, updated_at, merged_at, + removal_branch, removal_pr_number, removal_pr_url` func scanPages(rows *sql.Rows) ([]SitePage, error) { defer rows.Close() @@ -104,7 +125,7 @@ func scanPages(rows *sql.Rows) ([]SitePage, error) { var merged sql.NullString if err := rows.Scan(&p.ID, &p.Site, &p.Repo, &p.Kind, &src, &p.Notes, &p.Path, &p.Title, &p.Description, &p.Sections, &needs, &warns, &claims, &p.Status, &p.Branch, &p.File, &p.PRNumber, &p.PRURL, &p.Note, &p.Error, - &created, &updated, &merged); err != nil { + &created, &updated, &merged, &p.RemovalBranch, &p.RemovalPRNumber, &p.RemovalPRURL); err != nil { return nil, err } _ = json.Unmarshal([]byte(src), &p.Source) @@ -154,6 +175,36 @@ func Pages(d *db.DB, site string) ([]SitePage, error) { return scanPages(rows) } +// SignalPages lists a buying signal's pages, on every site, oldest first +// (so variants follow the page they're made from). +func SignalPages(d *db.DB, signal int64) ([]SitePage, error) { + rows, err := d.Query(`SELECT `+pageCols+` FROM site_pages WHERE json_extract(source, '$.signal') = ? ORDER BY id`, signal) + if err != nil { + return nil, err + } + return scanPages(rows) +} + +// LivePageCounts is how many pages each signal has on the published sites. +func LivePageCounts(d *db.DB) (map[int64]int, error) { + rows, err := d.Query(`SELECT json_extract(source, '$.signal'), count(*) FROM site_pages + WHERE status IN (?, ?) AND json_extract(source, '$.signal') IS NOT NULL GROUP BY 1`, PageMerged, PageRemoving) + if err != nil { + return nil, err + } + defer rows.Close() + out := map[int64]int{} + for rows.Next() { + var sig int64 + var n int + if err := rows.Scan(&sig, &n); err != nil { + return nil, err + } + out[sig] = n + } + return out, rows.Err() +} + // PagesIn lists pages in the given statuses, for every site. func PagesIn(d *db.DB, statuses ...string) ([]SitePage, error) { var all []SitePage @@ -188,11 +239,13 @@ func SavePage(d *db.DB, p *SitePage) error { p.Status = PageDraft } res, err := d.Exec(`INSERT INTO site_pages (site, repo, kind, source, notes, path, title, description, sections, needs, warnings, - claims, status, branch, file, pr_number, pr_url, note, error, created_at, updated_at, merged_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + claims, status, branch, file, pr_number, pr_url, note, error, created_at, updated_at, merged_at, + removal_branch, removal_pr_number, removal_pr_url) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, p.Site, p.Repo, p.Kind, string(src), p.Notes, p.Path, p.Title, p.Description, p.Sections, jsonText(p.Needs), jsonText(p.Warnings), jsonText(p.Claims), p.Status, p.Branch, p.File, p.PRNumber, p.PRURL, p.Note, p.Error, - p.CreatedAt.UTC().Format(time.RFC3339), now.Format(time.RFC3339), merged) + p.CreatedAt.UTC().Format(time.RFC3339), now.Format(time.RFC3339), merged, + p.RemovalBranch, p.RemovalPRNumber, p.RemovalPRURL) if err != nil { return err } @@ -201,9 +254,10 @@ func SavePage(d *db.DB, p *SitePage) error { } res, err := d.Exec(`UPDATE site_pages SET site = ?, repo = ?, kind = ?, source = ?, notes = ?, path = ?, title = ?, description = ?, sections = ?, needs = ?, warnings = ?, claims = ?, status = ?, branch = ?, file = ?, pr_number = ?, pr_url = ?, note = ?, error = ?, - updated_at = ?, merged_at = ? WHERE id = ?`, + updated_at = ?, merged_at = ?, removal_branch = ?, removal_pr_number = ?, removal_pr_url = ? WHERE id = ?`, p.Site, p.Repo, p.Kind, string(src), p.Notes, p.Path, p.Title, p.Description, p.Sections, jsonText(p.Needs), jsonText(p.Warnings), - jsonText(p.Claims), p.Status, p.Branch, p.File, p.PRNumber, p.PRURL, p.Note, p.Error, now.Format(time.RFC3339), merged, p.ID) + jsonText(p.Claims), p.Status, p.Branch, p.File, p.PRNumber, p.PRURL, p.Note, p.Error, now.Format(time.RFC3339), merged, + p.RemovalBranch, p.RemovalPRNumber, p.RemovalPRURL, p.ID) if err != nil { return err } diff --git a/internal/tracking/tracking.go b/internal/tracking/tracking.go index 97a6743..75c80bc 100644 --- a/internal/tracking/tracking.go +++ b/internal/tracking/tracking.go @@ -232,3 +232,40 @@ func plausibleSite(v string) string { } return v } + +// SiteID is a website's Plausible site ID: its Plausible site if set, else +// its domain. +func SiteID(w profile.Website) string { + if site := plausibleSite(w.PlausibleSite); site != "" { + return site + } + if u, err := url.Parse(strings.TrimSpace(w.URL)); err == nil { + return strings.TrimPrefix(strings.ToLower(u.Hostname()), "www.") + } + return "" +} + +// PageVisitors is each page's visitors over the last 30 days, by path, for +// comparing a landing page with its variants. Counted per page, never per +// person. +func PageVisitors(ctx context.Context, c *plausible.Client, site string, paths []string) (map[string]int, error) { + out := map[string]int{} + if len(paths) == 0 { + return out, nil + } + var ps []any + for _, p := range paths { + ps = append(ps, p) + } + rows, err := c.Run(ctx, plausible.Query{SiteID: site, Metrics: []string{"visitors"}, DateRange: "30d", + Dimensions: []string{"event:page"}, Filters: [][]any{{"is", "event:page", ps}}}) + if err != nil { + return nil, err + } + for _, r := range rows { + if len(r.Dimensions) > 0 && len(r.Metrics) > 0 { + out[r.Dimensions[0]] = int(r.Metrics[0]) + } + } + return out, nil +} diff --git a/internal/web/signals.go b/internal/web/signals.go index 92d5283..87607e3 100644 --- a/internal/web/signals.go +++ b/internal/web/signals.go @@ -9,6 +9,8 @@ import ( "net/url" "strconv" "strings" + "supermarket/internal/sites" + "supermarket/internal/tracking" "time" "supermarket/internal/ai" @@ -64,7 +66,13 @@ func (s *Server) renderSignals(w http.ResponseWriter, r *http.Request, errMsg st s.serverError(w, err) return } + live, err := sites.LivePageCounts(s.DB) + if err != nil { + s.serverError(w, err) + return + } s.render(w, r, "signals", page{Title: "Signals", Nav: "prospects/signals", Error: errMsg, Data: map[string]any{ + "LivePages": live, "Rows": rows, "Signals": list, "Stages": signals.Stages, @@ -92,6 +100,10 @@ type signalData struct { Posts []content.Draft // written for it Links []string // the websites, tagged with its campaign + Pages []signalPage // its landing pages and their variants + PageSites []siteRepo // websites a landing page can go on + VisitorsErr string // why page visitors couldn't be read + Runs []discovery.Run Running bool Research string // why Claude can't search, or "" @@ -101,6 +113,13 @@ type signalData struct { MaxResults int } +// signalPage is a landing page on a signal's page. +type signalPage struct { + sites.SitePage + Address string // on the live site + Visitors int // last 30 days; -1 when unknown +} + type channelRow struct { Channel string Row signals.Row @@ -171,6 +190,10 @@ func (s *Server) renderSignal(w http.ResponseWriter, r *http.Request, sig *signa s.serverError(w, err) return } + if err := s.signalPages(r.Context(), sig, &d); err != nil { + s.serverError(w, err) + return + } cs, ps, err := prospects.Review(s.DB, prospects.StatusNew, sig.ID, 1000) if err != nil { s.serverError(w, err) @@ -667,3 +690,61 @@ func tagLink(site, slug string) string { u.RawQuery = q.Encode() return u.String() } + +// signalPages fills in a signal's landing pages: their state on Gitea +// (merged, closed), and each live one's visitors over 30 days. +func (s *Server) signalPages(ctx context.Context, sig *signals.Signal, d *signalData) error { + ps, err := sites.SignalPages(s.DB, sig.ID) + if err != nil { + return err + } + for _, sr := range s.siteRepos() { + if sr.Repo != "" { + d.PageSites = append(d.PageSites, sr) + } + } + if s.gitea() != nil { + gctx, cancel := context.WithTimeout(ctx, 15*time.Second) + for i := range ps { + if ps[i].Status == sites.PagePR || ps[i].Status == sites.PageRemoving { + s.refreshPagePR(gctx, &ps[i]) + } + } + cancel() + } + prof, _ := profile.Load(s.DB) + bySite := map[string][]string{} + for _, p := range ps { + if p.Live() { + bySite[p.Site] = append(bySite[p.Site], p.Path) + } + } + visitors := map[string]map[string]int{} + if pl := s.plausible(); pl != nil && prof != nil && len(bySite) > 0 { + pctx, cancel := context.WithTimeout(ctx, 15*time.Second) + for _, w := range prof.Websites { + paths := bySite[w.URL] + if len(paths) == 0 { + continue + } + v, err := tracking.PageVisitors(pctx, pl, tracking.SiteID(w), paths) + if err != nil { + d.VisitorsErr = err.Error() + continue + } + visitors[w.URL] = v + } + cancel() + } + for _, p := range ps { + sp := signalPage{SitePage: p, Visitors: -1} + if p.Live() { + sp.Address = strings.TrimRight(p.Site, "/") + p.Path + if v, ok := visitors[p.Site]; ok { + sp.Visitors = v[p.Path] + } + } + d.Pages = append(d.Pages, sp) + } + return nil +} diff --git a/internal/web/sitepages.go b/internal/web/sitepages.go index d26502c..016e715 100644 --- a/internal/web/sitepages.go +++ b/internal/web/sitepages.go @@ -131,7 +131,7 @@ func (s *Server) compose(ctx context.Context, cur siteRepo, p *sites.SitePage, p // checkPage checks the sections; a problem is kept as the page's error, // for the user to fix in the YAML. func (s *Server) checkPage(cat *sites.Catalog, p *sites.SitePage, campaign string) error { - ch, err := sites.Check(cat, p.Sections, p.Site, campaign) + ch, err := sites.Check(cat, p.Sections, p.Site, campaign, sites.Content(p)) if err != nil { p.Error, p.Warnings, p.Claims = "Fix this before pushing: "+err.Error(), nil, nil return nil @@ -233,7 +233,7 @@ func (s *Server) renderSitePage(w http.ResponseWriter, r *http.Request, errMsg, errMsg = "" // the page shows its own } cur, ok := s.pageSite(p) - if p.Status == sites.PagePR && s.gitea() != nil { + if (p.Status == sites.PagePR || p.Status == sites.PageRemoving) && s.gitea() != nil { ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) s.refreshPagePR(ctx, p) cancel() @@ -270,10 +270,30 @@ func (s *Server) renderSitePage(w http.ResponseWriter, r *http.Request, errMsg, s.render(w, r, "sites-page", page{Title: or(p.Title, "New page"), Nav: "sites/pages", Error: errMsg, Flash: flash, Data: data}) } -// refreshPagePR notes when a page's pull request is merged or closed. +// refreshPagePR notes when a page's pull request (adding or removing it) +// is merged or closed. func (s *Server) refreshPagePR(ctx context.Context, p *sites.SitePage) { _, full, err := gitea.ParseRepo(p.Repo) - if err != nil || p.PRNumber == 0 { + if err != nil { + return + } + if p.Status == sites.PageRemoving { + pull, err := s.gitea().GetPull(ctx, full, p.RemovalPRNumber) + if err != nil { + return + } + switch { + case pull.Merged: + p.Status = sites.PageRemoved + case pull.State == "closed": + p.Status, p.RemovalPRNumber, p.RemovalPRURL = sites.PageMerged, 0, "" + default: + return + } + _ = sites.SavePage(s.DB, p) + return + } + if p.PRNumber == 0 { return } pull, err := s.gitea().GetPull(ctx, full, p.PRNumber) @@ -316,15 +336,62 @@ func (s *Server) sitePageAction(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/sites/pages", http.StatusSeeOther) return } - if !p.Editable() { - s.renderSitePage(w, r, "This page can't be changed here any more.", "") - return - } cur, ok := s.pageSite(p) if !ok { s.renderSitePage(w, r, "This page's website or repository isn't in the profile any more.", "") return } + back := "/sites/pages/" + strconv.FormatInt(id, 10) + if ret := r.PostFormValue("return"); strings.HasPrefix(ret, "/signals/") && !strings.Contains(ret, "//") { + back = ret + } + switch action { + case "duplicate": + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Minute) + defer cancel() + v, err := sites.Variant(s.DB, p) + if err != nil { + s.serverError(w, err) + return + } + if notes := strings.TrimSpace(r.PostFormValue("variant_notes")); notes != "" { + v.Notes = notes + if err := s.compose(ctx, cur, v, true); err != nil { + v.Error = "Couldn't write the variant: " + err.Error() + } + } else if cat, err := s.catalog(ctx, cur, false); err == nil { + _ = s.checkPage(cat, v, s.campaignOf(v)) // its links get its own utm_content + } + if err := sites.SavePage(s.DB, v); err != nil { + s.serverError(w, err) + return + } + http.Redirect(w, r, "/sites/pages/"+strconv.FormatInt(v.ID, 10), http.StatusSeeOther) + return + case "remove", "close": + if s.gitea() == nil { + s.renderSitePage(w, r, "Save a Gitea token under Settings → Search engines first.", "") + return + } + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Minute) + defer cancel() + var err error + if action == "remove" { + err = sites.Remove(ctx, s.DB, s.applier(seoSite{Index: cur.Index, URL: cur.URL}), p) + } else { + err = sites.ClosePR(ctx, s.DB, s.gitea(), cur.Repo, p) + } + if err != nil { + s.renderSitePage(w, r, err.Error(), "") + return + } + http.Redirect(w, r, back, http.StatusSeeOther) + return + } + if !p.Editable() { + s.renderSitePage(w, r, "This page can't be changed here any more.", "") + return + } // Every action keeps the user's edits first. if _, has := r.PostForm["sections"]; has { p.Title = strings.TrimSpace(r.PostFormValue("title")) diff --git a/internal/web/sites_test.go b/internal/web/sites_test.go index bdbe1c9..3ce6090 100644 --- a/internal/web/sites_test.go +++ b/internal/web/sites_test.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "fmt" + "io" "net/http" "net/http/httptest" "net/url" @@ -16,6 +17,7 @@ import ( "supermarket/internal/ai" "supermarket/internal/signals" + "supermarket/internal/sites" "supermarket/internal/hugorepo" "supermarket/internal/hugorepo/hugotest" @@ -305,3 +307,139 @@ func TestSitePageBuilder(t *testing.T) { t.Errorf("after delete: %d", rec.Code) } } + +func TestSignalLandingPages(t *testing.T) { + if hugorepo.HugoVersion(context.Background()) == "" { + t.Skip("no hugo") + } + clone := hugotest.Site(t, map[string]string{ + "layouts/partials/render-sections.html": `{{ range .Params.sections }}{{ partial (printf "sections/%s.html" .type) . }}{{ end }}`, + "layouts/partials/sections/hero.html": `

{{ .title }}

{{ range .ctas }}{{ .label }}{{ end }}`, + "layouts/_default/single.html": `{{ define "main" }}

{{ .Title }}

{{ partial "render-sections.html" . }}{{ .Content }}{{ end }}`, + "content/landing.md": "---\ntitle: Landing\nsections:\n - type: hero\n title: Hello\n---\n", + }) + var opened []map[string]string + merged := map[string]bool{} + var closed []string + g := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + const repo = "/api/v1/repos/Us/site" + switch { + case r.URL.Path == repo: + fmt.Fprintf(w, `{"full_name":"Us/site","default_branch":"main","clone_url":%q,"permissions":{"push":true}}`, clone) + case r.URL.Path == repo+"/pulls" && r.Method == http.MethodPost: + var body map[string]string + json.NewDecoder(r.Body).Decode(&body) + opened = append(opened, body) + fmt.Fprintf(w, `{"number":%d,"state":"open","html_url":"https://gitea.example/pulls/%d"}`, len(opened), len(opened)) + case strings.HasPrefix(r.URL.Path, repo+"/pulls/") && r.Method == http.MethodPatch: + closed = append(closed, strings.TrimPrefix(r.URL.Path, repo+"/pulls/")) + fmt.Fprint(w, `{}`) + case strings.HasPrefix(r.URL.Path, repo+"/pulls/"): + n := strings.TrimPrefix(r.URL.Path, repo+"/pulls/") + if merged[n] { + fmt.Fprintf(w, `{"number":%s,"state":"closed","merged":true,"merged_at":"2026-11-22T10:00:00Z"}`, n) + } else { + fmt.Fprintf(w, `{"number":%s,"state":"open"}`, n) + } + default: + http.NotFound(w, r) + } + })) + defer g.Close() + var plausibleQuery string + pl := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + raw, _ := io.ReadAll(r.Body) + plausibleQuery = string(raw) + fmt.Fprint(w, `{"results":[{"dimensions":["/for-churches/"],"metrics":[42]},{"dimensions":["/for-churches-b/"],"metrics":[7]}]}`) + })) + defer pl.Close() + composed, _ := json.Marshal(map[string]any{"path": "/for-churches/", "title": "For churches", "description": "d", + "sections_yaml": "- type: hero\n title: One bill\n ctas:\n - label: Start\n url: /pricing/\n", "needs": []string{}}) + newAIClient = func(ai.Config, *secrets.Store) (ai.Client, error) { return cannedAI{string(composed)}, nil } + defer func() { newAIClient = ai.New }() + + s, h := newTestServer(t, nil) + profile.Save(s.DB, &profile.Profile{Name: "Us", Description: "Widgets.", Websites: []profile.Website{{URL: "https://us.example/", Repo: "Us/site"}}}) + sig := &signals.Signal{Name: "Churches", Slug: "churches", Status: "testing"} + signals.Save(s.DB, sig) + sigURL := "/signals/" + strconv.FormatInt(sig.ID, 10) + postForm(h, "/settings/search", url.Values{"gitea_url": {g.URL}, secrets.GiteaToken: {"tok"}}) + s.DB.PutJSON(plausibleURLKey, pl.URL) + s.Secrets.Set(map[string]string{secrets.PlausibleAPIKey: "pk"}) + + body := do(h, http.MethodGet, sigURL, nil, nil).Body.String() + if !strings.Contains(body, "No landing page for this signal yet") || !strings.Contains(body, `name="signal" value="`+strconv.FormatInt(sig.ID, 10)) { + t.Errorf("before: %s", body) + } + // Built from the signal's page, pushed with a pull request, merged. + postForm(h, "/sites/pages", url.Values{"site": {"0"}, "kind": {"landing"}, "signal": {strconv.FormatInt(sig.ID, 10)}}) + postForm(h, "/sites/pages/1/pr", url.Values{"title": {"For churches"}, "description": {"d"}, "path": {"/for-churches/"}, + "sections": {"- type: hero\n title: One bill\n ctas:\n - label: Start\n url: /pricing/\n"}}) + if len(opened) != 1 { + t.Fatalf("no pull request: %v", opened) + } + merged["1"] = true // and really merged: main moves to the page's branch + if out, err := exec.Command("git", "--git-dir", strings.TrimPrefix(clone, "file://"), "update-ref", "refs/heads/main", "refs/heads/supermarket/site-page-1").CombinedOutput(); err != nil { + t.Fatalf("merge: %s", out) + } + body = do(h, http.MethodGet, sigURL, nil, nil).Body.String() + if !strings.Contains(body, `href="https://us.example/for-churches/"`) || !strings.Contains(body, ">merged<") || !strings.Contains(body, "42") || + !strings.Contains(body, "Remove from the site") { + t.Errorf("live page: %s", body) + } + if !strings.Contains(plausibleQuery, `"site_id":"us.example"`) || !strings.Contains(plausibleQuery, `"/for-churches/"`) { + t.Errorf("plausible query: %s", plausibleQuery) + } + if body := do(h, http.MethodGet, "/signals", nil, nil).Body.String(); !strings.Contains(body, `title="Landing pages on your website">1 page<`) { + t.Errorf("scorecard: %s", body) + } + + // A variant: its own address, B, links with its own utm_content. + rec := postForm(h, "/sites/pages/1/duplicate", url.Values{}) + if rec.Header().Get("Location") != "/sites/pages/2" { + t.Fatalf("duplicate: %d %s", rec.Code, rec.Body.String()) + } + body = do(h, http.MethodGet, "/sites/pages/2", nil, nil).Body.String() + if !strings.Contains(body, `value="/for-churches-b/"`) || !strings.Contains(body, "Variant B") || + !strings.Contains(body, "utm_campaign=churches&utm_content=for-churches-b&utm_medium=landing") { + t.Errorf("variant: %s", body) + } + // A second one is C. + postForm(h, "/sites/pages/2/duplicate", url.Values{}) + if p, _ := sites.GetPage(s.DB, 3); p.Path != "/for-churches-c/" || p.Source.Variant != "C" || p.Source.VariantOf != 1 { + t.Errorf("third: %+v", p) + } + if p, _ := sites.GetPage(s.DB, 1); p.Source.Variant != "A" { + t.Errorf("original: %+v", p.Source) + } + // Variant B goes up as a pull request, then is closed without merging. + postForm(h, "/sites/pages/2/pr", url.Values{"title": {"For churches B"}, "description": {"d"}, "path": {"/for-churches-b/"}, + "sections": {"- type: hero\n title: Shorter\n"}}) + postForm(h, "/sites/pages/2/close", url.Values{"return": {sigURL}}) + if p, _ := sites.GetPage(s.DB, 2); p.Status != sites.PageClosed || len(closed) != 1 || closed[0] != "2" { + t.Errorf("closed: %s %v", p.Status, closed) + } + + // Removing the original: a pull request deleting its file. + rec = postForm(h, "/sites/pages/1/remove", url.Values{"return": {sigURL}}) + if rec.Header().Get("Location") != sigURL || len(opened) != 3 { + t.Fatalf("remove: %d %s %v", rec.Code, rec.Body.String(), opened) + } + if pr := opened[2]; pr["head"] != "supermarket/remove-site-page-1" || pr["title"] != "Sites: remove /for-churches/" { + t.Errorf("removal pull request: %v", pr) + } + out, _ := exec.Command("git", "--git-dir", strings.TrimPrefix(clone, "file://"), "ls-tree", "-r", "--name-only", "supermarket/remove-site-page-1").CombinedOutput() + if strings.Contains(string(out), "for-churches.md") || !strings.Contains(string(out), "landing.md") { + t.Errorf("files on the removal branch: %s", out) + } + if body := do(h, http.MethodGet, sigURL, nil, nil).Body.String(); !strings.Contains(body, "removal pull request open") { + t.Errorf("removing: %s", body) + } + merged["3"] = true + if body := do(h, http.MethodGet, sigURL, nil, nil).Body.String(); !strings.Contains(body, ">removed<") { + t.Errorf("removed: %s", body) + } + if body := do(h, http.MethodGet, "/signals", nil, nil).Body.String(); strings.Contains(body, "Landing pages on your website") { + t.Error("still counted as live") + } +} diff --git a/internal/web/static/app.css b/internal/web/static/app.css index 38689c8..deb2fd2 100644 --- a/internal/web/static/app.css +++ b/internal/web/static/app.css @@ -445,3 +445,10 @@ svg.chart text { font-size: 9px; fill: hsl(var(--muted-foreground)); } table.cohorts td, table.cohorts th { padding-left: 0.4rem; padding-right: 0.4rem; font-size: 0.85rem; } .table-wrap { overflow-x: auto; } table.compact th, table.compact td { white-space: nowrap; padding-left: 0.5rem; padding-right: 0.5rem; font-size: 0.85rem; } +/* A button that opens a small form below it (Sites: variants). */ +details.inline-details { display: inline-block; vertical-align: top; } +details.inline-details > summary { list-style: none; cursor: pointer; } +details.inline-details > summary::-webkit-details-marker { display: none; } +details.inline-details[open] { display: block; white-space: normal; margin: 0.4rem 0; } +details.inline-details form { margin-top: 0.5rem; min-width: 18rem; } +.button.small { padding: 0.28rem 0.75rem; font-size: 0.82rem; } diff --git a/internal/web/templates/layout.html b/internal/web/templates/layout.html index d347d1a..202b338 100644 --- a/internal/web/templates/layout.html +++ b/internal/web/templates/layout.html @@ -195,5 +195,7 @@ {{- else if eq .Status "merged"}}merged {{- else if eq .Status "closed"}}closed {{- else if eq .Status "failed"}}failed +{{- else if eq .Status "removing"}}removal pull request open +{{- else if eq .Status "removed"}}removed {{- end}}{{if and .Error (ne .Status "failed")}} to fix{{end}} {{end}} diff --git a/internal/web/templates/signal.html b/internal/web/templates/signal.html index 16be266..06f5ca2 100644 --- a/internal/web/templates/signal.html +++ b/internal/web/templates/signal.html @@ -97,6 +97,48 @@
    {{range $i, $u := .}}
  • {{$u}}
  • {{end}}
{{end}} +

Landing pages

+{{$sig := $s}} +{{if .Pages}} +
+ + {{range .Pages}} + + + + + {{end}} +
PageStatusVisitors, 30 days
{{with .Source.Variant}}{{.}} {{end}}{{or .Title "Untitled"}}
+ {{if .Address}}{{.Address}}{{else}}{{.Site}}{{.Path}}{{end}}
{{template "page-status" .}}{{if ge .Visitors 0}}{{.Visitors}}{{else}}—{{end}}
+
Duplicate as a variant +
+ + +
+
+ {{if eq .Status "merged"}}
+
{{end}} + {{if or (eq .Status "pr") (eq .Status "removing")}}
+
{{end}} +
+{{with .VisitorsErr}}

Couldn't read visitors from Plausible: {{.}}

{{end}} +

Visitors are everyone who saw the page, however they came. A variant's links to your site carry its own utm_content, so sign-ups that keep the tags can be told apart.

+{{else}}

No landing page for this signal yet.

{{end}} +{{if .PageSites}} +
+ +
+ {{if gt (len .PageSites) 1}} + {{else}}{{range .PageSites}}{{end}}{{end}} + +
+ + + Its links to your site carry utm_campaign={{$s.Slug}}. You review it before anything goes to Gitea. +
+{{else}}

Landing pages need a website with a Hugo repository in Settings → Profile.

{{end}} + {{if .Events}}

Latest steps

diff --git a/internal/web/templates/signals.html b/internal/web/templates/signals.html index e0786ab..cc17ce3 100644 --- a/internal/web/templates/signals.html +++ b/internal/web/templates/signals.html @@ -22,7 +22,7 @@ {{range .Rows}} - + {{range .Cells}}{{end}} diff --git a/internal/web/templates/sites-page.html b/internal/web/templates/sites-page.html index 9c47483..3888b7a 100644 --- a/internal/web/templates/sites-page.html +++ b/internal/web/templates/sites-page.html @@ -11,6 +11,8 @@ {{end}} +{{with $p.Source.Variant}}

Variant {{.}}{{if $p.Source.VariantOf}} of the original page{{end}}.{{if $p.Source.VariantOf}} Its links to your site carry their own utm_content.{{end}}

{{end}} +{{with $p.RemovalPRURL}}

The pull request that takes it off the site: {{.}} ↗

{{end}} {{with $p.Error}}{{end}} {{if $p.Editable}} @@ -50,6 +52,25 @@
{{$p.Sections}}
{{end}} +
+ + + + + {{if eq $p.Status "merged"}} +
+ + Opens a pull request deleting the page; merging takes it off. + + {{end}} + {{if or (eq $p.Status "pr") (eq $p.Status "removing")}} +
+ + + {{end}} +
+ Forgets the page here. Its branch and pull request on Gitea stay; close them there.
{{with .Signal}}{{.Name}} {{.Status}}{{else}}No signal{{end}}{{with .Signal}}{{.Name}} {{.Status}}{{with index $.Data.LivePages .ID}} {{.}} page{{if ne . 1}}s{{end}}{{end}}{{else}}No signal{{end}}{{if .Count}}{{.Count}}{{with .Rate}}{{.}}{{end}}{{else}}·{{end}}{{if .RevenueCents}}{{money .RevenueCents}}{{else}}·{{end}} {{if .SpendCents}}{{money .SpendCents}}{{else}}·{{end}}