Phase 5 part 3: build pages from a site's own sections
Sites → New pages: the AI composes a landing, product, alternative, comparison or blog page as the site's own sections, from the profile and optionally a product, competitor, buying signal or SEO brief. Code checks every section type, warns on unknown fields and missing pages, tags a signal's links with its campaign and finds experience claims. Pages are edited here, pushed to their own branch with a preview, and opened as pull requests after the claims are confirmed. Schema 22. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -17,6 +17,7 @@ import (
|
||||
"supermarket/internal/profile"
|
||||
"supermarket/internal/secrets"
|
||||
"supermarket/internal/seo"
|
||||
"supermarket/internal/sites"
|
||||
)
|
||||
|
||||
var googleFields = []secretField{
|
||||
@@ -248,6 +249,9 @@ func (s *Server) RunSEO(ctx context.Context) {
|
||||
if err := seo.RecoverBriefs(s.DB); err != nil {
|
||||
s.Log.Error("seo: recovering briefs", "err", err)
|
||||
}
|
||||
if err := sites.RecoverPages(s.DB); err != nil {
|
||||
s.Log.Error("sites: recovering pages", "err", err)
|
||||
}
|
||||
tick := time.NewTicker(30 * time.Minute)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
|
||||
@@ -28,6 +28,7 @@ import (
|
||||
"supermarket/internal/secrets"
|
||||
"supermarket/internal/seo"
|
||||
"supermarket/internal/signals"
|
||||
"supermarket/internal/sites"
|
||||
)
|
||||
|
||||
//go:embed templates/*.html
|
||||
@@ -178,6 +179,10 @@ func (s *Server) Handler() (http.Handler, error) {
|
||||
mux.HandleFunc("POST /metrics/customers/{id}", s.metricsCustomerMatch)
|
||||
mux.HandleFunc("GET /sites", s.sitesPage)
|
||||
mux.HandleFunc("POST /sites/sync", s.sitesSync)
|
||||
mux.HandleFunc("GET /sites/pages", s.sitePagesPage)
|
||||
mux.HandleFunc("POST /sites/pages", s.sitePageNew)
|
||||
mux.HandleFunc("GET /sites/pages/{id}", s.sitePagePage)
|
||||
mux.HandleFunc("POST /sites/pages/{id}/{action}", s.sitePageAction)
|
||||
mux.HandleFunc("GET /sites/previews", s.sitesPreviewsPage)
|
||||
mux.HandleFunc("POST /sites/previews/build", s.sitesPreviewBuild)
|
||||
mux.HandleFunc("POST /sites/previews/delete", s.sitesPreviewDelete)
|
||||
@@ -307,6 +312,7 @@ func (s *Server) loadTemplates() error {
|
||||
"join": strings.Join,
|
||||
"ago": ago,
|
||||
"ticks": ticks,
|
||||
"kindLabel": sites.KindLabel,
|
||||
"add": func(a, b int) int { return a + b },
|
||||
"hasPrefix": strings.HasPrefix,
|
||||
"sourceLabel": prospects.SourceLabel,
|
||||
@@ -416,6 +422,8 @@ func (p page) Section() string {
|
||||
return "Settings"
|
||||
case p.Nav == "inventory":
|
||||
return "Inventory"
|
||||
case strings.HasPrefix(p.Nav, "sites"):
|
||||
return "Sites"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -100,7 +100,7 @@ func TestEveryPageRenders(t *testing.T) {
|
||||
"/settings/ai", "/settings/accounts", "/settings/core", "/static/app.css", "/favicon.ico", "/static/favicon.png", "/static/logo.png", "/static/apple-touch-icon.png", "/search", "/crm", "/search?q=rival", "/search?q=nothing+here", "/static/htmx.min.js", "/healthz",
|
||||
"/content", "/content/1", "/content/1?dismissed=1", "/posts", "/posts?msg=drafted",
|
||||
"/content/scheduled", "/content/published",
|
||||
"/prospects", "/prospects?status=accepted", "/prospects?status=rejected", "/prospects/new", "/prospects/suppressed", "/outreach", "/outreach?tab=queued", "/outreach?tab=sent", "/outreach?tab=replied", "/outreach?tab=failed", "/settings/email", "/settings/tracking", "/settings/search", "/seo", "/seo/check", "/seo/report", "/seo/audit", "/seo/changes", "/seo/keywords", "/seo/briefs", "/seo/engines", "/metrics", "/metrics/customers", "/metrics/customers?show=all", "/metrics/spend", "/metrics/clv", "/metrics/clv?view=profit", "/metrics/publish", "/sites", "/sites?site=0", "/sites/previews",
|
||||
"/prospects", "/prospects?status=accepted", "/prospects?status=rejected", "/prospects/new", "/prospects/suppressed", "/outreach", "/outreach?tab=queued", "/outreach?tab=sent", "/outreach?tab=replied", "/outreach?tab=failed", "/settings/email", "/settings/tracking", "/settings/search", "/seo", "/seo/check", "/seo/report", "/seo/audit", "/seo/changes", "/seo/keywords", "/seo/briefs", "/seo/engines", "/metrics", "/metrics/customers", "/metrics/customers?show=all", "/metrics/spend", "/metrics/clv", "/metrics/clv?view=profit", "/metrics/publish", "/sites", "/sites?site=0", "/sites/previews", "/sites/pages",
|
||||
"/signals", "/signals?period=30d&channel=email", "/signals/new", "/settings/sources"} {
|
||||
rec := do(h, http.MethodGet, path, nil, nil)
|
||||
if rec.Code != http.StatusOK {
|
||||
|
||||
@@ -0,0 +1,396 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/api/gitea"
|
||||
"supermarket/internal/hugorepo"
|
||||
"supermarket/internal/inventory"
|
||||
"supermarket/internal/profile"
|
||||
"supermarket/internal/seo"
|
||||
"supermarket/internal/signals"
|
||||
"supermarket/internal/sites"
|
||||
)
|
||||
|
||||
// catalog reads the site's sections from its working copy: fresh from the
|
||||
// repository, or as last read.
|
||||
func (s *Server) catalog(ctx context.Context, cur siteRepo, fresh bool) (*sites.Catalog, error) {
|
||||
if fresh {
|
||||
ap := s.applier(seoSite{Index: cur.Index, URL: cur.URL})
|
||||
wc, _, branch, err := ap.WorkingCopy(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer wc.Release()
|
||||
_ = s.DB.PutJSON(siteSyncKey(cur.Repo), siteSynced{At: time.Now(), Branch: branch})
|
||||
return sites.Read(wc.Dir, wc.PathOf)
|
||||
}
|
||||
var synced siteSynced
|
||||
if ok, _ := s.DB.GetJSON(siteSyncKey(cur.Repo), &synced); !ok || synced.At.IsZero() {
|
||||
return nil, errors.New("read the site's repository under Sites → Sections and pages first")
|
||||
}
|
||||
wc := &hugorepo.Repo{Dir: s.siteDir(cur.Repo), Branch: synced.Branch}
|
||||
wc.Acquire()
|
||||
defer wc.Release()
|
||||
return sites.Read(wc.Dir, wc.PathOf)
|
||||
}
|
||||
|
||||
func (s *Server) pageSite(p *sites.SitePage) (siteRepo, bool) {
|
||||
for _, sr := range s.siteRepos() {
|
||||
if strings.TrimRight(sr.URL, "/") == strings.TrimRight(p.Site, "/") && sr.Repo != "" {
|
||||
return sr, true
|
||||
}
|
||||
}
|
||||
return siteRepo{}, false
|
||||
}
|
||||
|
||||
// pageInputs looks up what a page is built from.
|
||||
func (s *Server) pageInputs(p *sites.SitePage, prof *profile.Profile) (sites.Inputs, string, error) {
|
||||
in := sites.Inputs{Kind: p.Kind, Notes: p.Notes, Path: p.Path, SiteURL: p.Site}
|
||||
campaign := ""
|
||||
if name := p.Source.Product; name != "" {
|
||||
for i := range prof.Products {
|
||||
if prof.Products[i].Name == name {
|
||||
in.Product = &prof.Products[i]
|
||||
}
|
||||
}
|
||||
}
|
||||
if id := p.Source.Competitor; id != 0 {
|
||||
e, err := inventory.Get(s.DB, id)
|
||||
if err != nil {
|
||||
return in, "", errors.New("that competitor isn't in the Inventory any more")
|
||||
}
|
||||
in.Competitor = e
|
||||
}
|
||||
if id := p.Source.Signal; id != 0 {
|
||||
sig, err := signals.Get(s.DB, id)
|
||||
if err != nil {
|
||||
return in, "", errors.New("that buying signal is gone")
|
||||
}
|
||||
in.Signal, campaign = sig, sig.Slug
|
||||
}
|
||||
if id := p.Source.Brief; id != 0 {
|
||||
b, err := seo.GetBrief(s.DB, id)
|
||||
if err != nil {
|
||||
return in, "", errors.New("that SEO brief is gone")
|
||||
}
|
||||
in.Brief = b
|
||||
}
|
||||
return in, campaign, nil
|
||||
}
|
||||
|
||||
func (s *Server) campaignOf(p *sites.SitePage) string {
|
||||
if p.Source.Signal == 0 {
|
||||
return ""
|
||||
}
|
||||
if sig, err := signals.Get(s.DB, p.Source.Signal); err == nil {
|
||||
return sig.Slug
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// compose has the AI write the page (again), then checks it.
|
||||
func (s *Server) compose(ctx context.Context, cur siteRepo, p *sites.SitePage, previous bool) error {
|
||||
client, prof, err := s.draftClient()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if prof == nil || !prof.IsSet() {
|
||||
return errors.New("fill in the company profile under Settings → Profile first")
|
||||
}
|
||||
cat, err := s.catalog(ctx, cur, true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
in, campaign, err := s.pageInputs(p, prof)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
in.Catalog = cat
|
||||
if previous {
|
||||
prev := *p
|
||||
in.Previous = &prev
|
||||
}
|
||||
out, err := (&sites.Composer{AI: client, Profile: prof}).Compose(ctx, in)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
p.Title, p.Description, p.Needs = out.Title, out.Description, out.Needs
|
||||
if p.File == "" { // the address can't move once the file is on a branch
|
||||
p.Path = out.Path
|
||||
}
|
||||
p.Sections = out.Sections
|
||||
return s.checkPage(cat, p, campaign)
|
||||
}
|
||||
|
||||
// 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)
|
||||
if err != nil {
|
||||
p.Error, p.Warnings, p.Claims = "Fix this before pushing: "+err.Error(), nil, nil
|
||||
return nil
|
||||
}
|
||||
p.Sections, p.Warnings, p.Claims, p.Error = ch.Sections, ch.Warnings, ch.Claims, ""
|
||||
return nil
|
||||
}
|
||||
|
||||
// --- The list ---
|
||||
|
||||
func (s *Server) sitePagesPage(w http.ResponseWriter, r *http.Request) {
|
||||
s.renderSitePages(w, r, "")
|
||||
}
|
||||
|
||||
func (s *Server) renderSitePages(w http.ResponseWriter, r *http.Request, errMsg string) {
|
||||
all, cur := s.currentSite(r)
|
||||
data := map[string]any{"Sites": all, "Current": cur, "Kinds": sites.Kinds, "Gitea": s.gitea() != nil}
|
||||
if cur != nil && cur.Repo != "" {
|
||||
ps, err := sites.Pages(s.DB, cur.URL)
|
||||
if err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
data["Pages"] = ps
|
||||
var synced siteSynced
|
||||
ok, _ := s.DB.GetJSON(siteSyncKey(cur.Repo), &synced)
|
||||
data["HasSynced"] = ok && !synced.At.IsZero()
|
||||
}
|
||||
prof, _ := profile.Load(s.DB)
|
||||
if prof != nil {
|
||||
data["Products"] = prof.Products
|
||||
}
|
||||
data["Competitors"], _ = inventory.List(s.DB, "competitor")
|
||||
data["Signals"], _ = signals.List(s.DB)
|
||||
if cur != nil {
|
||||
var briefs []seo.Brief
|
||||
bs, _ := seo.Briefs(s.DB, cur.URL)
|
||||
for _, b := range bs {
|
||||
if b.Page == "" && b.Plan.Title != "" {
|
||||
briefs = append(briefs, b)
|
||||
}
|
||||
}
|
||||
data["Briefs"] = briefs
|
||||
}
|
||||
cfg, _ := aiConfigured(s)
|
||||
data["AI"] = cfg
|
||||
s.render(w, r, "sites-pages", page{Title: "Pages", Nav: "sites/pages", Error: errMsg, Data: data})
|
||||
}
|
||||
|
||||
func aiConfigured(s *Server) (bool, error) {
|
||||
_, _, err := s.draftClient()
|
||||
return err == nil, err
|
||||
}
|
||||
|
||||
// sitePageNew composes a new page.
|
||||
func (s *Server) sitePageNew(w http.ResponseWriter, r *http.Request) {
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
_, cur := s.currentSite(r)
|
||||
if cur == nil || cur.Repo == "" {
|
||||
s.renderSitePages(w, r, "Set this website's Hugo repository in Settings → Profile first.")
|
||||
return
|
||||
}
|
||||
p := &sites.SitePage{Site: cur.URL, Repo: cur.Repo, Kind: r.PostFormValue("kind"),
|
||||
Notes: strings.TrimSpace(r.PostFormValue("notes")), Path: sites.CleanPath(r.PostFormValue("path"))}
|
||||
p.Source.Product = r.PostFormValue("product")
|
||||
p.Source.Competitor, _ = strconv.ParseInt(r.PostFormValue("competitor"), 10, 64)
|
||||
p.Source.Signal, _ = strconv.ParseInt(r.PostFormValue("signal"), 10, 64)
|
||||
p.Source.Brief, _ = strconv.ParseInt(r.PostFormValue("brief"), 10, 64)
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Minute)
|
||||
defer cancel()
|
||||
if err := s.compose(ctx, *cur, p, false); err != nil {
|
||||
s.renderSitePages(w, r, err.Error())
|
||||
return
|
||||
}
|
||||
if err := sites.SavePage(s.DB, p); err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
http.Redirect(w, r, "/sites/pages/"+strconv.FormatInt(p.ID, 10), http.StatusSeeOther)
|
||||
}
|
||||
|
||||
// --- One page ---
|
||||
|
||||
func (s *Server) sitePagePage(w http.ResponseWriter, r *http.Request) {
|
||||
s.renderSitePage(w, r, "", "")
|
||||
}
|
||||
|
||||
func (s *Server) renderSitePage(w http.ResponseWriter, r *http.Request, errMsg, flash string) {
|
||||
id, _ := strconv.ParseInt(r.PathValue("id"), 10, 64)
|
||||
p, err := sites.GetPage(s.DB, id)
|
||||
if err != nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if errMsg == p.Error {
|
||||
errMsg = "" // the page shows its own
|
||||
}
|
||||
cur, ok := s.pageSite(p)
|
||||
if p.Status == sites.PagePR && s.gitea() != nil {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
|
||||
s.refreshPagePR(ctx, p)
|
||||
cancel()
|
||||
}
|
||||
data := map[string]any{"P": p, "Kind": sites.KindLabel(p.Kind), "Gitea": s.gitea() != nil, "Site": cur, "HasSite": ok}
|
||||
if ok && p.Branch != "" {
|
||||
for _, pv := range s.previews(cur.Repo) {
|
||||
if pv.Branch == p.Branch && pv.Commit != "" {
|
||||
data["Preview"] = previewPrefix(cur.Index, pv.Slug) + strings.TrimPrefix(p.Path, "/")
|
||||
data["PreviewAt"] = pv.At
|
||||
}
|
||||
}
|
||||
}
|
||||
var from []string
|
||||
if p.Source.Product != "" {
|
||||
from = append(from, "the product "+p.Source.Product)
|
||||
}
|
||||
if p.Source.Competitor != 0 {
|
||||
if e, err := inventory.Get(s.DB, p.Source.Competitor); err == nil {
|
||||
from = append(from, "the competitor "+e.Name)
|
||||
}
|
||||
}
|
||||
if p.Source.Signal != 0 {
|
||||
if sig, err := signals.Get(s.DB, p.Source.Signal); err == nil {
|
||||
from = append(from, "the buying signal “"+sig.Name+"” (links tagged utm_campaign="+sig.Slug+")")
|
||||
}
|
||||
}
|
||||
if p.Source.Brief != 0 {
|
||||
if b, err := seo.GetBrief(s.DB, p.Source.Brief); err == nil {
|
||||
from = append(from, "the SEO brief for “"+b.Keyword+"”")
|
||||
}
|
||||
}
|
||||
data["From"] = from
|
||||
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.
|
||||
func (s *Server) refreshPagePR(ctx context.Context, p *sites.SitePage) {
|
||||
_, full, err := gitea.ParseRepo(p.Repo)
|
||||
if err != nil || p.PRNumber == 0 {
|
||||
return
|
||||
}
|
||||
pull, err := s.gitea().GetPull(ctx, full, p.PRNumber)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
switch {
|
||||
case pull.Merged:
|
||||
p.Status = sites.PageMerged
|
||||
if pull.MergedAt != nil {
|
||||
p.MergedAt = *pull.MergedAt
|
||||
} else {
|
||||
p.MergedAt = time.Now()
|
||||
}
|
||||
case pull.State == "closed":
|
||||
p.Status = sites.PageClosed
|
||||
default:
|
||||
return
|
||||
}
|
||||
_ = sites.SavePage(s.DB, p)
|
||||
}
|
||||
|
||||
func (s *Server) sitePageAction(w http.ResponseWriter, r *http.Request) {
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
id, _ := strconv.ParseInt(r.PathValue("id"), 10, 64)
|
||||
p, err := sites.GetPage(s.DB, id)
|
||||
if err != nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
action := r.PathValue("action")
|
||||
if action == "delete" {
|
||||
if err := sites.DeletePage(s.DB, id); err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
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
|
||||
}
|
||||
// Every action keeps the user's edits first.
|
||||
if _, has := r.PostForm["sections"]; has {
|
||||
p.Title = strings.TrimSpace(r.PostFormValue("title"))
|
||||
p.Description = strings.TrimSpace(r.PostFormValue("description"))
|
||||
if p.File == "" {
|
||||
p.Path = sites.CleanPath(r.PostFormValue("path"))
|
||||
}
|
||||
p.Notes = strings.TrimSpace(r.PostFormValue("notes"))
|
||||
p.Sections = strings.TrimSpace(strings.ReplaceAll(r.PostFormValue("sections"), "\r\n", "\n"))
|
||||
p.Needs = lines(r.PostFormValue("needs"))
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Minute)
|
||||
defer cancel()
|
||||
switch action {
|
||||
case "save", "preview", "pr":
|
||||
cat, err := s.catalog(ctx, cur, false)
|
||||
if err != nil {
|
||||
s.renderSitePage(w, r, err.Error(), "")
|
||||
return
|
||||
}
|
||||
_ = s.checkPage(cat, p, s.campaignOf(p))
|
||||
case "rewrite":
|
||||
if err := s.compose(ctx, cur, p, true); err != nil {
|
||||
_ = sites.SavePage(s.DB, p)
|
||||
s.renderSitePage(w, r, err.Error(), "")
|
||||
return
|
||||
}
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if err := sites.SavePage(s.DB, p); err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
if action == "save" || action == "rewrite" {
|
||||
http.Redirect(w, r, "/sites/pages/"+strconv.FormatInt(id, 10), http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
if p.Error != "" {
|
||||
s.renderSitePage(w, r, p.Error, "")
|
||||
return
|
||||
}
|
||||
if action == "pr" {
|
||||
if err := sites.ConfirmedAll(p.Claims, r.PostForm["confirm"]); err != nil {
|
||||
s.renderSitePage(w, r, err.Error(), "")
|
||||
return
|
||||
}
|
||||
}
|
||||
if s.gitea() == nil {
|
||||
s.renderSitePage(w, r, "Save a Gitea token under Settings → Search engines first.", "")
|
||||
return
|
||||
}
|
||||
ap := s.applier(seoSite{Index: cur.Index, URL: cur.URL})
|
||||
if err := sites.Push(ctx, s.DB, ap, p, action == "pr"); err != nil {
|
||||
s.renderSitePage(w, r, err.Error(), "")
|
||||
return
|
||||
}
|
||||
flash := "Pushed to the branch " + p.Branch + "."
|
||||
if action == "pr" {
|
||||
flash = "The pull request is open."
|
||||
}
|
||||
if _, err := s.buildPreview(ctx, cur, p.Branch); err != nil {
|
||||
flash += " The preview didn't build: " + err.Error()
|
||||
} else {
|
||||
flash += " The preview is ready."
|
||||
}
|
||||
s.renderSitePage(w, r, "", flash)
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package web
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -9,9 +10,13 @@ import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"supermarket/internal/ai"
|
||||
"supermarket/internal/signals"
|
||||
|
||||
"supermarket/internal/hugorepo"
|
||||
"supermarket/internal/hugorepo/hugotest"
|
||||
"supermarket/internal/profile"
|
||||
@@ -177,3 +182,126 @@ func TestSitePreviews(t *testing.T) {
|
||||
t.Error("the files are still there")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSitePageBuilder(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/partials/sections/faq.html": "{{ $s := . }}{{ range $s.items }}<h3>{{ .q }}</h3>{{ .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 ctas:\n - label: Go\n url: /pricing/\n style: primary\n---\n",
|
||||
})
|
||||
var pulls []url.Values
|
||||
g := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.URL.Path == "/api/v1/repos/Us/site":
|
||||
fmt.Fprintf(w, `{"full_name":"Us/site","default_branch":"main","clone_url":%q,"permissions":{"push":true}}`, clone)
|
||||
case r.URL.Path == "/api/v1/repos/Us/site/pulls" && r.Method == http.MethodPost:
|
||||
var body map[string]string
|
||||
json.NewDecoder(r.Body).Decode(&body)
|
||||
pulls = append(pulls, url.Values{"head": {body["head"]}, "base": {body["base"]}, "title": {body["title"]}, "body": {body["body"]}})
|
||||
fmt.Fprint(w, `{"number":7,"state":"open","html_url":"https://gitea.example/Us/site/pulls/7"}`)
|
||||
case r.URL.Path == "/api/v1/repos/Us/site/pulls/7":
|
||||
fmt.Fprint(w, `{"number":7,"state":"closed","merged":true,"merged_at":"2026-11-22T10:00:00Z","html_url":"https://gitea.example/Us/site/pulls/7"}`)
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer g.Close()
|
||||
composed, _ := json.Marshal(map[string]any{"path": "/for-churches/", "title": "For churches", "description": "One bill for your church.",
|
||||
"sections_yaml": "- type: hero\n title: Run your church on one bill\n ctas:\n - label: Start\n url: /pricing/\n style: primary\n- type: faq\n items:\n - q: Does it work?\n a: We tested it with our own team.\n",
|
||||
"needs": []string{"A real quote from a church"}})
|
||||
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"}
|
||||
if err := signals.Save(s.DB, sig); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if body := do(h, http.MethodGet, "/sites/pages", nil, nil).Body.String(); !strings.Contains(body, "Gitea token") || !strings.Contains(body, "No pages built yet") {
|
||||
t.Errorf("before: %s", body)
|
||||
}
|
||||
postForm(h, "/settings/search", url.Values{"gitea_url": {g.URL}, secrets.GiteaToken: {"tok"}})
|
||||
|
||||
rec := postForm(h, "/sites/pages", url.Values{"site": {"0"}, "kind": {"landing"}, "signal": {strconv.FormatInt(sig.ID, 10)}, "notes": {"for churches"}})
|
||||
if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/sites/pages/1" {
|
||||
t.Fatalf("new: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
body := do(h, http.MethodGet, "/sites/pages/1", nil, nil).Body.String()
|
||||
for _, want := range []string{"For churches", "/for-churches/", "the buying signal “Churches”", "url: /pricing/?utm_campaign=churches&utm_medium=landing",
|
||||
"A real quote from a church", `name="confirm" value="We tested it with our own team."`, "Open a pull request"} {
|
||||
if !strings.Contains(body, want) {
|
||||
t.Errorf("page lacks %q", want)
|
||||
}
|
||||
}
|
||||
if body := do(h, http.MethodGet, "/sites/pages", nil, nil).Body.String(); !strings.Contains(body, `href="/sites/pages/1">For churches`) {
|
||||
t.Errorf("list: %s", body)
|
||||
}
|
||||
|
||||
form := func(sections string, confirm ...string) url.Values {
|
||||
v := url.Values{"title": {"For churches"}, "description": {"One bill."}, "path": {"/for-churches/"}, "notes": {"for churches"},
|
||||
"sections": {sections}, "needs": {"A real quote from a church"}}
|
||||
v["confirm"] = confirm
|
||||
return v
|
||||
}
|
||||
// A section type the site doesn't have is caught on saving.
|
||||
postForm(h, "/sites/pages/1/save", form("- type: gizmo\n"))
|
||||
if body := do(h, http.MethodGet, "/sites/pages/1", nil, nil).Body.String(); !strings.Contains(body, `the site has no "gizmo" section`) {
|
||||
t.Errorf("bad type: %s", body)
|
||||
}
|
||||
good := "- type: hero\n title: Run your church on one bill\n ctas:\n - label: Start\n url: /pricing/\n- type: faq\n items:\n - q: Does it work?\n a: We tested it with our own team.\n"
|
||||
// …and pushing refuses until it's fixed.
|
||||
if body := postForm(h, "/sites/pages/1/preview", form("- type: gizmo\n")).Body.String(); !strings.Contains(body, "Fix this before pushing") {
|
||||
t.Errorf("pushed a bad page: %s", body)
|
||||
}
|
||||
|
||||
// Push and preview: the page is on its branch, built, and previewed.
|
||||
body = postForm(h, "/sites/pages/1/preview", form(good)).Body.String()
|
||||
if !strings.Contains(body, "Pushed to the branch supermarket/site-page-1. The preview is ready.") ||
|
||||
!strings.Contains(body, `href="/preview/0/supermarket-site-page-1/for-churches/"`) || len(pulls) != 0 {
|
||||
t.Errorf("preview: %s", body)
|
||||
}
|
||||
got := do(h, http.MethodGet, "/preview/0/supermarket-site-page-1/for-churches/", nil, nil).Body.String()
|
||||
if !strings.Contains(got, "<h1>For churches</h1>") || !strings.Contains(got, "Run your church on one bill") ||
|
||||
!strings.Contains(got, `href="/preview/0/supermarket-site-page-1/pricing/?utm_campaign=churches&utm_medium=landing"`) {
|
||||
t.Errorf("previewed page: %s", got)
|
||||
}
|
||||
|
||||
// The claim must be confirmed before the pull request.
|
||||
if body := postForm(h, "/sites/pages/1/pr", form(good)).Body.String(); !strings.Contains(body, "confirm or remove this claim first") || len(pulls) != 0 {
|
||||
t.Errorf("unconfirmed: %s", body)
|
||||
}
|
||||
body = postForm(h, "/sites/pages/1/pr", form(good, "We tested it with our own team.")).Body.String()
|
||||
if !strings.Contains(body, "The pull request is open.") || len(pulls) != 1 {
|
||||
t.Fatalf("pr: %s", body)
|
||||
}
|
||||
pr := pulls[0]
|
||||
if pr.Get("head") != "supermarket/site-page-1" || pr.Get("base") != "main" || pr.Get("title") != "Sites: landing page /for-churches/" ||
|
||||
!strings.Contains(pr.Get("body"), "We tested it with our own team.") || !strings.Contains(pr.Get("body"), "A real quote from a church") ||
|
||||
!strings.Contains(pr.Get("body"), "Checked with a build") {
|
||||
t.Errorf("pull request: %v", pr)
|
||||
}
|
||||
// The file is on the branch, with the address fixed.
|
||||
out, err := exec.Command("git", "--git-dir", strings.TrimPrefix(clone, "file://"), "show", "supermarket/site-page-1:content/for-churches.md").CombinedOutput()
|
||||
if err != nil || !strings.HasPrefix(string(out), "---\ntitle: For churches\n") || !strings.Contains(string(out), " - type: faq\n") {
|
||||
t.Errorf("the file: %v %s", err, out)
|
||||
}
|
||||
|
||||
// Gitea says it's merged: the page shows it, and can't be edited.
|
||||
body = do(h, http.MethodGet, "/sites/pages/1", nil, nil).Body.String()
|
||||
if !strings.Contains(body, ">merged<") || strings.Contains(body, `name="sections"`) {
|
||||
t.Errorf("merged: %s", body)
|
||||
}
|
||||
if body := postForm(h, "/sites/pages/1/save", form(good)).Body.String(); !strings.Contains(body, "can't be changed") {
|
||||
t.Errorf("edit after merge: %s", body)
|
||||
}
|
||||
postForm(h, "/sites/pages/1/delete", nil)
|
||||
if rec := do(h, http.MethodGet, "/sites/pages/1", nil, nil); rec.Code != http.StatusNotFound {
|
||||
t.Errorf("after delete: %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,6 +62,7 @@
|
||||
{{if eq .ID "sites"}}
|
||||
<div class="subnav">
|
||||
<a href="/sites" {{if eq $nav "sites/site"}}aria-current="page"{{end}}>Sections and pages</a>
|
||||
<a href="/sites/pages" {{if hasPrefix $nav "sites/pages"}}aria-current="page"{{end}}>New pages</a>
|
||||
<a href="/sites/previews" {{if eq $nav "sites/previews"}}aria-current="page"{{end}}>Previews</a>
|
||||
</div>
|
||||
{{end}}
|
||||
@@ -184,3 +185,15 @@
|
||||
<nav class="tabs">{{range .Sites}}<a href="{{$d.Path}}?site={{.Index}}" {{if eq .Index $d.Current.Index}}aria-current="page"{{end}}>{{.URL}}</a>{{end}}</nav>
|
||||
{{end}}
|
||||
{{end}}
|
||||
|
||||
{{/* A Sites page's status, as a badge. */}}
|
||||
{{define "page-status"}}
|
||||
{{- if eq .Status "draft"}}<span class="badge draft">draft</span>
|
||||
{{- else if eq .Status "working"}}<span class="badge scheduled">pushing…</span>
|
||||
{{- else if eq .Status "pushed"}}<span class="badge scheduled">on its branch</span>
|
||||
{{- else if eq .Status "pr"}}<span class="badge scheduled">pull request open</span>
|
||||
{{- 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>
|
||||
{{- end}}{{if and .Error (ne .Status "failed")}} <span class="badge failed">to fix</span>{{end}}
|
||||
{{end}}
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
{{define "content"}}{{with .Data}}{{$d := .}}{{$p := .P}}
|
||||
<div class="heading"><h1>{{or $p.Title "New page"}}</h1></div>
|
||||
<p class="lede">{{.Kind}} for {{$p.Site}}{{with .From}}, from {{join . "; "}}{{end}}.
|
||||
{{template "page-status" $p}}</p>
|
||||
|
||||
{{if or $p.PRURL .Preview}}
|
||||
<section class="card">
|
||||
{{with .Preview}}<p><a class="button" href="{{.}}" target="_blank" rel="noopener">Open the preview ↗</a> <span class="small muted">built {{ago $d.PreviewAt}} from the branch {{$p.Branch}}</span></p>{{end}}
|
||||
{{with $p.PRURL}}<p>The pull request: <a href="{{.}}" target="_blank" rel="noopener noreferrer">{{.}} ↗</a>{{if eq $p.Status "merged"}}, merged {{ago $p.MergedAt}}{{end}}</p>{{end}}
|
||||
{{with $p.Note}}<p class="small">{{.}}</p>{{end}}
|
||||
</section>
|
||||
{{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">
|
||||
<div class="cols">
|
||||
<label>Title <span class="muted">(for search results, under 60 characters)</span> <input name="title" value="{{$p.Title}}" maxlength="120"></label>
|
||||
<label>Address {{if $p.File}}<span class="muted">(fixed: the file is on its branch)</span>{{end}} <input name="path" value="{{$p.Path}}" {{if $p.File}}readonly{{end}}></label>
|
||||
</div>
|
||||
<label>Description <span class="muted">(under 155 characters)</span> <textarea name="description" rows="2">{{$p.Description}}</textarea></label>
|
||||
|
||||
{{with $p.Warnings}}
|
||||
<div class="warn card"><strong>To look at:</strong><ul>{{range .}}<li>{{.}}</li>{{end}}</ul></div>
|
||||
{{end}}
|
||||
|
||||
<label>Sections <span class="muted">(the page's front matter: your site's section types, as YAML)</span>
|
||||
<textarea name="sections" rows="28" class="mono" spellcheck="false">{{$p.Sections}}</textarea></label>
|
||||
<label>Still to add or check by hand <span class="muted">(one per line; listed in the pull request)</span>
|
||||
<textarea name="needs" rows="3">{{lines $p.Needs}}</textarea></label>
|
||||
<label>What the page is for <span class="muted">(used when it's written again)</span>
|
||||
<textarea name="notes" rows="3">{{$p.Notes}}</textarea></label>
|
||||
|
||||
{{with $p.Claims}}
|
||||
<fieldset><legend>Confirm these are true before the pull request</legend>
|
||||
<p class="small muted">They claim experience, tests or results. Tick each one that's true; edit the sections to take out any that aren't.</p>
|
||||
{{range .}}<label class="check"><input type="checkbox" name="confirm" value="{{.}}"> {{.}}</label>{{end}}
|
||||
</fieldset>
|
||||
{{end}}
|
||||
|
||||
<div class="actions">
|
||||
<button type="submit" class="secondary">Save</button>
|
||||
<button type="submit" class="secondary" formaction="/sites/pages/{{$p.ID}}/rewrite" data-busy="Writing…">Write it again</button>
|
||||
<button type="submit" class="secondary" formaction="/sites/pages/{{$p.ID}}/preview" data-busy="Pushing and building…" {{if not $d.Gitea}}disabled{{end}}>Push and preview</button>
|
||||
<button type="submit" formaction="/sites/pages/{{$p.ID}}/pr" data-busy="Opening…" {{if not $d.Gitea}}disabled{{end}}>{{if $p.PRNumber}}Update the pull request{{else}}Open a pull request{{end}}</button>
|
||||
</div>
|
||||
<p class="small muted"><em>Write it again</em> uses your notes above and keeps what you've edited as its starting point. <em>Push and preview</em> puts the page on its own branch ({{or $p.Branch "supermarket/site-page-…"}}) and builds a preview, without a pull request.</p>
|
||||
</form>
|
||||
{{else}}
|
||||
<section class="card"><pre class="sample">{{$p.Sections}}</pre></section>
|
||||
{{end}}
|
||||
|
||||
<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>
|
||||
</form>
|
||||
{{end}}{{end}}
|
||||
@@ -0,0 +1,62 @@
|
||||
{{define "content"}}{{with .Data}}{{$d := .}}
|
||||
<div class="heading"><h1>New pages</h1></div>
|
||||
<p class="lede">Pages for your website built from its own sections: a landing page, a product page, an alternative to a competitor, a comparison, or a blog post. The AI uses only the section types and fields your site already has. You review and edit the page here, preview it on its branch, and open a pull request; merging publishes it.</p>
|
||||
|
||||
{{if not .Sites}}
|
||||
<section class="card empty"><p>Add your website and its Hugo repository under <a href="/settings/profile">Settings → Profile</a> first.</p></section>
|
||||
{{else}}
|
||||
{{if gt (len .Sites) 1}}<nav class="tabs">{{range .Sites}}<a href="/sites/pages?site={{.Index}}" {{if and $d.Current (eq .Index $d.Current.Index)}}aria-current="page"{{end}}>{{.URL}}</a>{{end}}</nav>{{end}}
|
||||
{{with .Current}}{{$cur := .}}
|
||||
{{if .Err}}
|
||||
<section class="card"><p class="warn-text">{{.URL}}: {{.Err}}. Set it under <a href="/settings/profile">Settings → Profile</a>.</p></section>
|
||||
{{else}}
|
||||
<form method="post" action="/sites/pages" class="card">
|
||||
<h2>A new page</h2>
|
||||
<input type="hidden" name="site" value="{{.Index}}">
|
||||
{{if not $d.AI}}<p class="warn-text">Building pages needs the AI: choose a provider under <a href="/settings/ai">Settings → AI</a>.</p>{{end}}
|
||||
{{if not $d.Gitea}}<p class="warn-text">Supermarket reads the site with your Gitea token: save one under <a href="/settings/search">Settings → Search engines</a>.</p>{{end}}
|
||||
<div class="cols">
|
||||
<label>Kind of page
|
||||
<select name="kind">{{range $d.Kinds}}<option value="{{.ID}}">{{.Label}}</option>{{end}}</select>
|
||||
</label>
|
||||
<label>Address <span class="muted">(optional)</span> <input name="path" placeholder="/for-churches/"></label>
|
||||
</div>
|
||||
<div class="cols">
|
||||
<label>Product <span class="muted">(optional)</span>
|
||||
<select name="product"><option value="">None</option>{{range $d.Products}}<option>{{.Name}}</option>{{end}}</select>
|
||||
</label>
|
||||
<label>Competitor <span class="muted">(alternative and comparison pages)</span>
|
||||
<select name="competitor"><option value="">None</option>{{range $d.Competitors}}<option value="{{.ID}}">{{.Name}}</option>{{end}}</select>
|
||||
</label>
|
||||
</div>
|
||||
<div class="cols">
|
||||
<label>Buying signal <span class="muted">(optional; its links get the signal's campaign tag)</span>
|
||||
<select name="signal"><option value="">None</option>{{range $d.Signals}}<option value="{{.ID}}">{{.Name}}</option>{{end}}</select>
|
||||
</label>
|
||||
<label>SEO brief <span class="muted">(optional)</span>
|
||||
<select name="brief"><option value="">None</option>{{range $d.Briefs}}<option value="{{.ID}}">{{.Keyword}}</option>{{end}}</select>
|
||||
</label>
|
||||
</div>
|
||||
<label>What the page is for <textarea name="notes" rows="3" placeholder="Who it's for, what it should get them to do, anything it must or mustn't say."></textarea></label>
|
||||
<div class="actions">
|
||||
<button type="submit" data-busy="Reading the site and writing…" {{if or (not $d.AI) (not $d.Gitea)}}disabled{{end}}>Build the page</button>
|
||||
</div>
|
||||
<p class="small muted">It reads the site's repository first, so it uses the latest sections. Writing takes a minute or two.</p>
|
||||
</form>
|
||||
|
||||
<h2>Pages</h2>
|
||||
{{with $d.Pages}}
|
||||
<div class="table-wrap"><table>
|
||||
<thead><tr><th>Page</th><th>Kind</th><th>Status</th><th>Started</th></tr></thead>
|
||||
<tbody>{{range .}}<tr>
|
||||
<td><a href="/sites/pages/{{.ID}}">{{or .Title "Untitled"}}</a><br><span class="small muted">{{.Path}}</span></td>
|
||||
<td class="small">{{kindLabel .Kind}}</td>
|
||||
<td>{{template "page-status" .}}</td>
|
||||
<td class="small">{{ago .CreatedAt}}</td>
|
||||
</tr>{{end}}</tbody>
|
||||
</table></div>
|
||||
{{else}}<p class="help">No pages built yet.</p>{{end}}
|
||||
{{end}}
|
||||
{{end}}
|
||||
{{end}}
|
||||
{{end}}{{end}}
|
||||
Reference in New Issue
Block a user