Phase 5 part 4: landing pages per buying signal

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 <noreply@anthropic.com>
This commit is contained in:
2026-11-22 14:19:55 -07:00
co-authored by Claude Opus 5.5
parent 11b80b6461
commit 062fcf2e59
17 changed files with 674 additions and 33 deletions
+5
View File
@@ -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)
+6
View File
@@ -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 '';
`,
}
+13
View File
@@ -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",
+132 -6
View File
@@ -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)
}
+3 -3
View File
@@ -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)
}
+68 -14
View File
@@ -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
}
+37
View File
@@ -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
}
+81
View File
@@ -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
}
+75 -8
View File
@@ -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"))
+138
View File
@@ -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": `<h2>{{ .title }}</h2>{{ range .ctas }}<a href="{{ .url }}">{{ .label }}</a>{{ end }}`,
"layouts/_default/single.html": `{{ define "main" }}<h1>{{ .Title }}</h1>{{ 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, "<td>42</td>") ||
!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 <strong>B</strong>") ||
!strings.Contains(body, "utm_campaign=churches&amp;utm_content=for-churches-b&amp;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")
}
}
+7
View File
@@ -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; }
+2
View File
@@ -195,5 +195,7 @@
{{- else if eq .Status "merged"}}<span class="badge published">merged</span>
{{- else if eq .Status "closed"}}<span class="badge">closed</span>
{{- else if eq .Status "failed"}}<span class="badge failed">failed</span>
{{- else if eq .Status "removing"}}<span class="badge scheduled">removal pull request open</span>
{{- else if eq .Status "removed"}}<span class="badge">removed</span>
{{- end}}{{if and .Error (ne .Status "failed")}} <span class="badge failed">to fix</span>{{end}}
{{end}}
+42
View File
@@ -97,6 +97,48 @@
<ul class="small">{{range $i, $u := .}}<li><code id="link-{{$i}}">{{$u}}</code> <button type="button" class="link small" data-copy="link-{{$i}}">Copy</button></li>{{end}}</ul>
{{end}}
<h2>Landing pages</h2>
{{$sig := $s}}
{{if .Pages}}
<div class="table-wrap"><table>
<thead><tr><th>Page</th><th>Status</th><th>Visitors, 30 days</th><th></th></tr></thead>
<tbody>{{range .Pages}}<tr>
<td>{{with .Source.Variant}}<span class="badge">{{.}}</span> {{end}}<a href="/sites/pages/{{.ID}}">{{or .Title "Untitled"}}</a><br>
<span class="small muted">{{if .Address}}<a href="{{.Address}}" target="_blank" rel="noopener noreferrer">{{.Address}}</a>{{else}}{{.Site}}{{.Path}}{{end}}</span></td>
<td>{{template "page-status" .}}</td>
<td>{{if ge .Visitors 0}}{{.Visitors}}{{else}}<span class="muted">—</span>{{end}}</td>
<td><div class="row-actions">
<details class="inline-details"><summary class="button secondary small">Duplicate as a variant</summary>
<form method="post" action="/sites/pages/{{.ID}}/duplicate">
<label class="small">What to change in the variant <span class="muted">(optional: empty makes an exact copy to edit)</span>
<textarea name="variant_notes" rows="2" placeholder="A shorter page, with the price in the hero."></textarea></label>
<button type="submit" class="small" data-busy="Making it…">Make the variant</button>
</form>
</details>
{{if eq .Status "merged"}}<form method="post" action="/sites/pages/{{.ID}}/remove" data-confirm="Open a pull request that takes {{.Path}} off the site?">
<input type="hidden" name="return" value="/signals/{{$sig.ID}}"><button type="submit" class="secondary small" data-busy="Opening…">Remove from the site</button></form>{{end}}
{{if or (eq .Status "pr") (eq .Status "removing")}}<form method="post" action="/sites/pages/{{.ID}}/close" data-confirm="Close the pull request without merging?">
<input type="hidden" name="return" value="/signals/{{$sig.ID}}"><button type="submit" class="secondary small">Close the pull request</button></form>{{end}}
</div></td>
</tr>{{end}}</tbody>
</table></div>
{{with .VisitorsErr}}<p class="small warn-text">Couldn't read visitors from Plausible: {{.}}</p>{{end}}
<p class="small muted">Visitors are everyone who saw the page, however they came. A variant's links to your site carry its own <code>utm_content</code>, so sign-ups that keep the tags can be told apart.</p>
{{else}}<p class="help">No landing page for this signal yet.</p>{{end}}
{{if .PageSites}}
<form method="post" action="/sites/pages" class="card">
<input type="hidden" name="kind" value="landing"><input type="hidden" name="signal" value="{{$s.ID}}">
<div class="cols">
{{if gt (len .PageSites) 1}}<label>Website <select name="site">{{range .PageSites}}<option value="{{.Index}}">{{.URL}}</option>{{end}}</select></label>
{{else}}{{range .PageSites}}<input type="hidden" name="site" value="{{.Index}}">{{end}}{{end}}
<label>Address <span class="muted">(optional)</span> <input name="path" placeholder="/{{$s.Slug}}/"></label>
</div>
<label>What the page should do <span class="muted">(optional; the signal's angle is used)</span> <textarea name="notes" rows="2"></textarea></label>
<button type="submit" data-busy="Reading the site and writing…">Build a landing page for it</button>
<span class="small muted">Its links to your site carry utm_campaign={{$s.Slug}}. You review it before anything goes to Gitea.</span>
</form>
{{else}}<p class="small">Landing pages need a website with a Hugo repository in <a href="/settings/profile">Settings → Profile</a>.</p>{{end}}
{{if .Events}}
<h2>Latest steps</h2>
<table class="list">
+1 -1
View File
@@ -22,7 +22,7 @@
<tbody>
{{range .Rows}}
<tr>
<td>{{with .Signal}}<a href="/signals/{{.ID}}">{{.Name}}</a> <span class="badge {{.Status}}">{{.Status}}</span>{{else}}<span class="muted">No signal</span>{{end}}</td>
<td>{{with .Signal}}<a href="/signals/{{.ID}}">{{.Name}}</a> <span class="badge {{.Status}}">{{.Status}}</span>{{with index $.Data.LivePages .ID}} <span class="badge published" title="Landing pages on your website">{{.}} page{{if ne . 1}}s{{end}}</span>{{end}}{{else}}<span class="muted">No signal</span>{{end}}</td>
{{range .Cells}}<td class="num">{{if .Count}}{{.Count}}{{with .Rate}}<span class="rate">{{.}}</span>{{end}}{{else}}<span class="muted">·</span>{{end}}</td>{{end}}
<td class="num">{{if .RevenueCents}}{{money .RevenueCents}}{{else}}<span class="muted">·</span>{{end}}</td>
<td class="num">{{if .SpendCents}}{{money .SpendCents}}{{else}}<span class="muted">·</span>{{end}}</td>
+21
View File
@@ -11,6 +11,8 @@
</section>
{{end}}
{{with $p.Source.Variant}}<p class="small">Variant <strong>{{.}}</strong>{{if $p.Source.VariantOf}} of <a href="/sites/pages/{{$p.Source.VariantOf}}">the original page</a>{{end}}.{{if $p.Source.VariantOf}} Its links to your site carry their own <code>utm_content</code>.{{end}}</p>{{end}}
{{with $p.RemovalPRURL}}<p>The pull request that takes it off the site: <a href="{{.}}" target="_blank" rel="noopener noreferrer">{{.}} ↗</a></p>{{end}}
{{with $p.Error}}<p class="error" role="alert">{{.}}</p>{{end}}
{{if $p.Editable}}
<form method="post" action="/sites/pages/{{$p.ID}}/save" class="card">
@@ -50,6 +52,25 @@
<section class="card"><pre class="sample">{{$p.Sections}}</pre></section>
{{end}}
<section class="card">
<form method="post" action="/sites/pages/{{$p.ID}}/duplicate">
<label>Duplicate as a variant, to test against this one <span class="muted">(optional: what to change; empty makes an exact copy to edit)</span>
<textarea name="variant_notes" rows="2"></textarea></label>
<button type="submit" class="secondary" data-busy="Making it…">Make a variant</button>
</form>
{{if eq $p.Status "merged"}}
<form method="post" action="/sites/pages/{{$p.ID}}/remove" data-confirm="Open a pull request that takes {{$p.Path}} off the site?">
<button type="submit" class="secondary" data-busy="Opening…">Remove from the site</button>
<span class="small muted">Opens a pull request deleting the page; merging takes it off.</span>
</form>
{{end}}
{{if or (eq $p.Status "pr") (eq $p.Status "removing")}}
<form method="post" action="/sites/pages/{{$p.ID}}/close" data-confirm="Close the pull request without merging?">
<button type="submit" class="secondary">Close the pull request</button>
</form>
{{end}}
</section>
<form method="post" action="/sites/pages/{{$p.ID}}/delete" class="danger-zone">
<button type="submit" class="secondary" data-confirm="Forget this page? Its branch and pull request on Gitea stay.">Delete</button>
<span class="small muted">Forgets the page here. Its branch and pull request on Gitea stay; close them there.</span>