Phase 6 part 5, step 2: start a new site

Sites → New site fills an empty Gitea repository with the theme, a
hugo.toml in the site's brand and a starter home page: checked that the
repository is empty and builds with Hugo, then the first commit is pushed
to its default branch. The site joins the profile, and a First pages card
builds its Home, About, Contact and product pages with the page builder;
About and Contact join the top menu.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-22 15:27:22 -07:00
co-authored by Claude Opus 5.5
parent 5d7db5c5bf
commit 9ca09c1ffa
18 changed files with 709 additions and 7 deletions
+9 -4
View File
@@ -44,10 +44,15 @@ func (s *Server) gitea() *gitea.Client {
func (s *Server) applier(site seoSite) *seo.Applier {
p, _ := profile.Load(s.DB)
var repo, branch string
if p != nil && site.Index < len(p.Websites) {
if p != nil && site.Index >= 0 && site.Index < len(p.Websites) {
repo, branch = p.Websites[site.Index].Repo, p.Websites[site.Index].Branch
}
author := "Supermarket <supermarket@localhost>"
return &seo.Applier{Gitea: s.gitea(), Repo: repo, Branch: branch, ReposDir: filepath.Join(s.DataDir, "sites"), Author: s.commitAuthor()}
}
// commitAuthor is who Supermarket's commits are by: the Core's user, via
// Supermarket.
func (s *Server) commitAuthor() string {
if s.Core != nil && s.Core.Email != "" {
name := s.Core.Name
if name == "" {
@@ -55,9 +60,9 @@ func (s *Server) applier(site seoSite) *seo.Applier {
} else {
name += " (via Supermarket)"
}
author = name + " <" + s.Core.Email + ">"
return name + " <" + s.Core.Email + ">"
}
return &seo.Applier{Gitea: s.gitea(), Repo: repo, Branch: branch, ReposDir: filepath.Join(s.DataDir, "sites"), Author: author}
return "Supermarket <supermarket@localhost>"
}
func (s *Server) proposer() (*seo.Proposer, error) {
+78
View File
@@ -0,0 +1,78 @@
package web
import (
"context"
"net/http"
"strconv"
"strings"
"time"
"supermarket/internal/profile"
"supermarket/internal/sites"
)
func (s *Server) newSitePage(w http.ResponseWriter, r *http.Request) {
s.renderNewSite(w, r, sites.Defaults(), "")
}
func (s *Server) renderNewSite(w http.ResponseWriter, r *http.Request, n sites.NewSite, errMsg string) {
gitea := ""
if s.gitea() != nil {
gitea = s.giteaURL()
}
s.render(w, r, "sites-new", page{Title: "New site", Nav: "sites/new", Error: errMsg, Data: map[string]any{
"N": n, "Fonts": sites.Fonts, "Gitea": gitea,
}})
}
// newSiteCreate makes the new site: the first commit to its empty
// repository, then the site in the profile, read like the others.
func (s *Server) newSiteCreate(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
f := r.PostFormValue
n := sites.NewSite{Repo: f("repo"), URL: f("url"), Title: f("title"), Tagline: f("tagline"), Email: f("email"),
Dark: f("dark"), Primary: f("primary"), Accent: f("accent"), Font: f("font"), Logo: f("logo")}
if err := n.Check(); err != nil {
s.renderNewSite(w, r, n, err.Error())
return
}
prof, err := profile.Load(s.DB)
if err != nil {
s.serverError(w, err)
return
}
if prof == nil {
prof = &profile.Profile{}
}
for _, ws := range prof.Websites {
if strings.EqualFold(strings.TrimRight(ws.URL, "/"), n.URL) {
s.renderNewSite(w, r, n, n.URL+" is already one of your websites.")
return
}
}
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Minute)
defer cancel()
branch, err := sites.Create(ctx, s.gitea(), n, s.siteDir(n.Repo), s.commitAuthor())
if err != nil {
s.renderNewSite(w, r, n, err.Error())
return
}
prof.Websites = append(prof.Websites, profile.Website{URL: n.URL, Repo: n.Repo, Branch: branch})
if err := profile.Save(s.DB, prof); err != nil {
s.serverError(w, err)
return
}
_ = s.DB.PutJSON(siteSyncKey(n.Repo), siteSynced{At: time.Now(), Branch: branch})
index := 0
if p, _ := profile.Load(s.DB); p != nil {
for i, ws := range p.Websites {
if strings.TrimRight(ws.URL, "/") == n.URL {
index = i
}
}
}
http.Redirect(w, r, "/sites?site="+strconv.Itoa(index)+"&msg=site-created", http.StatusSeeOther)
}
+129
View File
@@ -0,0 +1,129 @@
package web
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"os/exec"
"path/filepath"
"strings"
"testing"
"supermarket/internal/ai"
"supermarket/internal/hugorepo"
"supermarket/internal/profile"
"supermarket/internal/secrets"
"supermarket/internal/sites"
)
func TestNewSite(t *testing.T) {
if hugorepo.HugoVersion(context.Background()) == "" {
t.Skip("no hugo")
}
bare := filepath.Join(t.TempDir(), "acme.git")
if out, err := exec.Command("git", "init", "--quiet", "--bare", "--initial-branch", "main", bare).CombinedOutput(); err != nil {
t.Fatalf("%s", out)
}
clone := "file://" + bare
empty := true
var opened []map[string]string
g := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/api/v1/repos/Us/acme":
fmt.Fprintf(w, `{"full_name":"Us/acme","default_branch":"main","clone_url":%q,"empty":%v,"permissions":{"push":true}}`, clone, empty)
case r.URL.Path == "/api/v1/repos/Us/acme/pulls" && r.Method == http.MethodPost:
var body map[string]string
json.NewDecoder(r.Body).Decode(&body)
opened = append(opened, body)
fmt.Fprint(w, `{"number":1,"state":"open","html_url":"https://gitea.example/pulls/1"}`)
default:
http.NotFound(w, r)
}
}))
defer g.Close()
s, h := newTestServer(t, nil)
profile.Save(s.DB, &profile.Profile{Name: "Acme", Description: "Widgets.", Websites: []profile.Website{{URL: "https://old.example"}}})
postForm(h, "/settings/search", url.Values{"gitea_url": {g.URL}, secrets.GiteaToken: {"tok"}})
if body := do(h, http.MethodGet, "/sites/new", nil, nil).Body.String(); !strings.Contains(body, g.URL+"/repo/create") || !strings.Contains(body, `value="#e0ff4f"`) {
t.Errorf("form: %s", body)
}
form := url.Values{"repo": {"Us/acme"}, "url": {"https://www.acme.example"}, "title": {"Acme Widgets"}, "tagline": {"Widgets for everyone"},
"email": {"hello@acme.example"}, "dark": {"#1d1238"}, "primary": {"#ffb703"}, "accent": {"#e4572e"}, "font": {"Manrope"}}
for field, bad := range map[string]string{"url": "http://acme.example", "dark": "purple", "repo": "nope", "title": " "} {
v := url.Values{}
for k, vs := range form {
v[k] = vs
}
v.Set(field, bad)
if rec := postForm(h, "/sites/new", v); rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `role="alert"`) {
t.Errorf("bad %s accepted: %d", field, rec.Code)
}
}
empty = false
if body := postForm(h, "/sites/new", form).Body.String(); !strings.Contains(body, "isn&#39;t empty") {
t.Errorf("non-empty repository: %s", body)
}
empty = true
rec := postForm(h, "/sites/new", form)
if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/sites?site=1&msg=site-created" {
t.Fatalf("create: %d %s", rec.Code, rec.Body.String())
}
show := func(ref, path string) string {
out, err := exec.Command("git", "--git-dir", bare, "show", ref+":"+path).CombinedOutput()
if err != nil {
t.Fatalf("%s %s: %s", ref, path, out)
}
return string(out)
}
cfg := show("main", "hugo.toml")
for _, want := range []string{`baseURL = "https://www.acme.example/"`, `title = "Acme Widgets"`, `theme = "supermarket"`, `primary = "#ffb703"`, `font = "Manrope"`, `email = "hello@acme.example"`} {
if !strings.Contains(cfg, want) {
t.Errorf("hugo.toml lacks %s:\n%s", want, cfg)
}
}
if v := show("main", "themes/supermarket/VERSION"); v != "1\n" || !strings.Contains(show("main", "content/_index.md"), "Widgets for everyone") {
t.Errorf("theme or home: %q", v)
}
p, _ := profile.Load(s.DB)
if len(p.Websites) != 2 || p.Websites[1].URL != "https://www.acme.example" || p.Websites[1].Repo != "Us/acme" || p.Websites[1].Branch != "main" {
t.Errorf("profile: %+v", p.Websites)
}
body := do(h, http.MethodGet, "/sites?site=1&msg=site-created", nil, nil).Body.String()
for _, want := range []string{"The site is started", "First pages", "version 1", ">Home page<", ">About page<", ">Contact page<", "<summary>form", "<summary>hero"} {
if !strings.Contains(body, want) {
t.Errorf("site page lacks %q", want)
}
}
// The same address again is refused.
if body := postForm(h, "/sites/new", form).Body.String(); !strings.Contains(body, "already one of your websites") {
t.Errorf("again: %s", body)
}
// A contact page from the theme's sections joins the top menu.
composed, _ := json.Marshal(map[string]any{"path": "/contact/", "title": "Contact", "description": "Write to us.",
"sections_yaml": "- type: hero\n title: Talk to us\n compact: true\n- type: form\n headline: Write to us\n subject: Contact\n fields:\n - { name: name, label: Name, required: true }\n - { name: email, label: Email, type: email, required: true }\n",
"needs": []string{}})
newAIClient = func(ai.Config, *secrets.Store) (ai.Client, error) { return cannedAI{string(composed)}, nil }
defer func() { newAIClient = ai.New }()
if rec := postForm(h, "/sites/pages", url.Values{"site": {"1"}, "kind": {"contact"}}); rec.Code != http.StatusSeeOther {
t.Fatalf("contact: %d %s", rec.Code, rec.Body.String())
}
pg, _ := sites.GetPage(s.DB, 1)
if pg.Error != "" || len(pg.Warnings) != 0 {
t.Errorf("contact page: %q %v", pg.Error, pg.Warnings)
}
postForm(h, "/sites/pages/1/pr", url.Values{"title": {pg.Title}, "description": {pg.Description}, "path": {pg.Path}, "sections": {pg.Sections}})
if len(opened) != 1 {
t.Fatalf("no pull request: %v", opened)
}
if fm := show("supermarket/site-page-1", "content/contact.md"); !strings.Contains(fm, "menus:\n main:\n weight: 90\n") {
t.Errorf("contact file:\n%s", fm)
}
if !strings.Contains(opened[0]["body"], "the page is at /contact/") {
t.Errorf("build check: %s", opened[0]["body"])
}
}
+3
View File
@@ -186,6 +186,8 @@ func (s *Server) Handler() (http.Handler, error) {
mux.HandleFunc("GET /sites/pages/{id}", s.sitePagePage)
mux.HandleFunc("POST /sites/pages/{id}/{action}", s.sitePageAction)
mux.HandleFunc("GET /sites/publishing", s.sitesPublishingPage)
mux.HandleFunc("GET /sites/new", s.newSitePage)
mux.HandleFunc("POST /sites/new", s.newSiteCreate)
mux.HandleFunc("GET /sites/forms", s.sitesFormsPage)
mux.HandleFunc("POST /sites/forms/{action}", s.sitesFormsAction)
mux.HandleFunc("GET /sites/previews", s.sitesPreviewsPage)
@@ -508,6 +510,7 @@ var flashes = map[string]string{
"deleted": "Deleted.",
"x-connected": "X is connected.",
"li-connected": "LinkedIn is connected.",
"site-created": "The site is started: its first commit is on Gitea. Build its first pages below.",
"li-page-connected": "The LinkedIn page app is connected.",
"google-connected": "Search Console is connected. Choose each website's property below, then sync.",
"synced": "Synced from Search Console.",
+1 -1
View File
@@ -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", "/sites/pages", "/sites/publishing", "/sites/forms", "/settings/backups",
"/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", "/sites/publishing", "/sites/forms", "/sites/new", "/settings/backups",
"/signals", "/signals?period=30d&channel=email", "/signals/new", "/settings/sources"} {
rec := do(h, http.MethodGet, path, nil, nil)
if rec.Code != http.StatusOK {
+8
View File
@@ -15,6 +15,7 @@ import (
"supermarket/internal/hugorepo"
"supermarket/internal/profile"
"supermarket/internal/sites"
"supermarket/internal/theme"
)
// siteRepo is a website with a Hugo repository, from the profile.
@@ -100,6 +101,13 @@ func (s *Server) renderSites(w http.ResponseWriter, r *http.Request, errMsg stri
cancel()
}
wc.Release()
if raw, rerr := os.ReadFile(filepath.Join(wc.Dir, theme.Dir, "VERSION")); rerr == nil {
data["Theme"] = strings.TrimSpace(string(raw))
data["Kinds"] = []string{"home", "about", "contact"}
if p, _ := profile.Load(s.DB); p != nil {
data["Products"] = p.Products
}
}
if err != nil {
errMsg = "Couldn't read the working copy: " + err.Error()
} else {
+2
View File
@@ -452,3 +452,5 @@ 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; }
input[type="color"] { height: 2.6rem; padding: 0.25rem; cursor: pointer; }
+1
View File
@@ -66,6 +66,7 @@
<a href="/sites/previews" {{if eq $nav "sites/previews"}}aria-current="page"{{end}}>Previews</a>
<a href="/sites/publishing" {{if eq $nav "sites/publishing"}}aria-current="page"{{end}}>Publishing</a>
<a href="/sites/forms" {{if eq $nav "sites/forms"}}aria-current="page"{{end}}>Lead forms</a>
<a href="/sites/new" {{if eq $nav "sites/new"}}aria-current="page"{{end}}>New site</a>
</div>
{{end}}
{{if eq .ID "prospects"}}
+39
View File
@@ -0,0 +1,39 @@
{{define "content"}}{{with .Data}}{{$n := .N}}
<div class="heading"><h1>A new site</h1></div>
<p class="lede">Start a website with Supermarket's theme: federated-website's look and sections, in your brand. Supermarket fills an empty Gitea repository with the theme, the settings and a starter home page; then you build its pages here, as pull requests.</p>
<section class="card">
<h2>1. In Gitea</h2>
<p>Create a new, <strong>empty</strong> repository{{with .Gitea}} on <a href="{{.}}/repo/create" target="_blank" rel="noopener noreferrer">{{.}}</a>{{end}}: no README, license or .gitignore. Supermarket makes its first commit.</p>
<p class="small muted">Publishing the site is your Gitea's job, as for your other sites: add the deploy hook that builds it with Hugo on your web server, and point the address below at it.</p>
{{if not .Gitea}}<p class="warn-text">Save a Gitea token under <a href="/settings/search">Settings → Search engines</a> first.</p>{{end}}
</section>
<form method="post" action="/sites/new" class="card">
<h2>2. The site</h2>
<div class="cols">
<label>Repository <input name="repo" value="{{$n.Repo}}" placeholder="owner/name" required></label>
<label>Its address <input name="url" value="{{$n.URL}}" placeholder="https://www.example.com" required></label>
</div>
<div class="cols">
<label>Name <input name="title" value="{{$n.Title}}" placeholder="Acme Widgets" required></label>
<label>Contact email <span class="muted">(where forms go until they're connected to EspoCRM)</span> <input name="email" type="email" value="{{$n.Email}}"></label>
</div>
<label>Tagline <input name="tagline" value="{{$n.Tagline}}" placeholder="What the company does, in a line."></label>
<h3>Brand</h3>
<div class="cols">
<label>Dark <span class="muted">(top bar, hero, closing band)</span> <input type="color" name="dark" value="{{$n.Dark}}"></label>
<label>Primary <span class="muted">(the main button)</span> <input type="color" name="primary" value="{{$n.Primary}}"></label>
<label>Accent <span class="muted">(links, highlights)</span> <input type="color" name="accent" value="{{$n.Accent}}"></label>
</div>
<div class="cols">
<label>Font <select name="font">{{range .Fonts}}<option {{if eq . $n.Font}}selected{{end}}>{{.}}</option>{{end}}</select></label>
<label>Logo <span class="muted">(optional: an image's https:// address, or a path on the site; without one, the name shows)</span> <input name="logo" value="{{$n.Logo}}"></label>
</div>
<div class="actions">
<button type="submit" data-busy="Starting the site…" {{if not .Gitea}}disabled{{end}}>Start the site</button>
</div>
<p class="small muted">It checks the repository is empty and builds the site with Hugo before pushing anything. Colors, font and logo can be changed later in the site's <code>hugo.toml</code>.</p>
</form>
{{end}}{{end}}
+17
View File
@@ -26,6 +26,23 @@
{{end}}
{{with .Catalog}}
{{if $d.Theme}}
<section class="card">
<h2>First pages</h2>
<p>This site uses Supermarket's theme (version {{$d.Theme}}). Build its pages: each is written from your profile, opens for you to edit and preview, and goes to the site as a pull request.</p>
<div class="row-actions">
{{range $d.Kinds}}
<form method="post" action="/sites/pages"><input type="hidden" name="site" value="{{$d.Current.Index}}"><input type="hidden" name="kind" value="{{.}}">
<button type="submit" class="secondary" data-busy="Writing…">{{kindLabel .}}</button></form>
{{end}}
{{range $d.Products}}
<form method="post" action="/sites/pages"><input type="hidden" name="site" value="{{$d.Current.Index}}"><input type="hidden" name="kind" value="product"><input type="hidden" name="product" value="{{.Name}}">
<button type="submit" class="secondary" data-busy="Writing…">Product page: {{.Name}}</button></form>
{{end}}
</div>
<p class="small muted">Each uses the AI (a paid call). About and Contact join the top menu; Contact has a lead form: connect it under <a href="/sites/forms?site={{$d.Current.Index}}">Lead forms</a>.</p>
</section>
{{end}}
{{with $d.Commits}}
<h2>Latest on the published branch</h2>
<div class="table-wrap"><table class="compact">